平凡也就兩個字: 懶和惰;
成功也就兩個字: 苦和勤;
優秀也就兩個字: 你和我。
跟着我從0學習JAVA、spring全家桶和linux運維等知識,帶你從懵懂少年走向人生巅峰,迎娶白富美!
關注微信公衆号【 IT特靠譜】,每天都會分享技術心得~
擷取本機IP位址和網卡的MAC位址
1 什麼是MAC位址?
MAC位址(英語:Media Access Control Address),直譯為媒體存取控制位址,也稱為區域網路位址(LAN Address),MAC位址,以太網位址(Ethernet Address)或實體位址(Physical Address),它是一個用來确認網絡裝置位置的位址。在OSI模型中,第三層網絡層負責IP位址,第二層資料鍊路層則負責MAC位址 。MAC位址用于在網絡中唯一标示一個網卡,一台裝置若有一個或多個網卡,則每個網卡都有一個唯一的MAC位址!
2 擷取IP位址和MAC位址
下面通過java來擷取本地ip位址和網卡MAC位址。
2.1 擷取IP位址
private static String getIpAddress() throws UnknownHostException {
InetAddress ia = InetAddress.getLocalHost();
return ia.getHostAddress();
}
2.2 擷取網卡的MAC位址
private static String getMacAddress() throws UnknownHostException, SocketException {
//擷取IP位址,輸出示例:WCGZ-DZ-013803/10.88.12.117
InetAddress ia = InetAddress.getLocalHost();
//擷取網卡的MAC位址
byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < mac.length; i++) {
if (i != 0) {
sb.append("-");
}
//位元組轉換為整數
int temp = mac[i] & 0xff;
String str = Integer.toHexString(temp);
if (str.length() == 1) {
sb.append("0" + str);
} else {
sb.append(str);
}
}
return sb.toString().toUpperCase();
}
3 完整代碼
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Main {
public static void main(String[] args) throws UnknownHostException, SocketException {
//擷取本機IP位址
String ip = getIpAddress();
//擷取本機網卡的MAC位址
String mac = getMacAddress();
log.info("IP位址為:{}, 本機網卡MAC位址為:{}", ip, mac);
}
private static String getIpAddress() throws UnknownHostException {
InetAddress ia = InetAddress.getLocalHost();
return ia.getHostAddress();
}
private static String getMacAddress() throws UnknownHostException, SocketException {
//擷取IP位址,輸出示例:WCGZ-DZ-013803/10.88.12.117
InetAddress ia = InetAddress.getLocalHost();
//擷取網卡的MAC位址
byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < mac.length; i++) {
if (i != 0) {
sb.append("-");
}
//位元組轉換為整數
int temp = mac[i] & 0xff;
String str = Integer.toHexString(temp);
if (str.length() == 1) {
sb.append("0" + str);
} else {
sb.append(str);
}
}
return sb.toString().toUpperCase();
}
}
4 測試結果

如果對你有幫助或需要技術支援,關注一下本人吧~