平凡也就兩個字: 懶和惰;
成功也就兩個字: 苦和勤;
優秀也就兩個字: 你和我。
跟著我從0學習JAVA、spring全家桶和linux運維等知識,帶你從懵懂少年走向人生巔峰,迎娶白富美!
每一篇文章都是心得總結,跟我學習你就是大牛!
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 { InetAddress ia = InetAddress.getLocalHost(); 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;
@Slf4jpublic class Main {
public static void main(String[] args) throws UnknownHostException, SocketException { String ip = getIpAddress(); 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 { InetAddress ia = InetAddress.getLocalHost(); 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 測試結果如果對你有幫助或需要技術支持,關注一下作者吧~