有些机器有许多虚拟的网卡,获取IP地址时会出现一些意外,所以需要一些验证: 1 // 获取mac地址 2 public static String getMacAddress() { 3 try { 4 Enumeration<NetworkIn ...
有些机器有许多虚拟的网卡,获取IP地址时会出现一些意外,所以需要一些验证:
1 // 获取mac地址 2 public static String getMacAddress() { 3 try { 4 Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces(); 5 byte[] mac = null; 6 while (allNetInterfaces.hasMoreElements()) { 7 NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); 8 if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) { 9 continue;10 } else {11 mac = netInterface.getHardwareAddress();12 if (mac != null) {13 StringBuilder sb = new StringBuilder();14 for (int i = 0; i < mac.length; i++) {15 sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));16 }17 if (sb.length() > 0) {18 return sb.toString();19 }20 }21 }22 }23 } catch (Exception e) {24 _logger.error("MAC地址获取失败", e);25 }26 return "";27 }28 29 // 获取ip地址30 public static String getIpAddress() {31 try {32 Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();33 InetAddress ip = null;34 while (allNetInterfaces.hasMoreElements()) {35 NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();36 if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {37 continue;38 } else {39 Enumeration<InetAddress> addresses = netInterface.getInetAddresses();40 while (addresses.hasMoreElements()) {41 ip = addresses.nextElement();42 if (ip != null && ip instanceof Inet4Address) {43 return ip.getHostAddress();44 }45 }46 }47 }48 } catch (Exception e) {49 _logger.error("IP地址获取失败", e);50 }51 return "";52 }
原标题:Java获取本机的IP与MAC地址
关键词:JAVA
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。