java 获取IP和MAC
2016-12-29 11:27
225 查看
java 获取IP和MAC
标签(空格分隔): javajava 获取IP和MAC
1获取IP
2获取mac
1、获取IP
public static String getIpAddress() { try { Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface)allNetInterfaces.nextElement(); if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) { continue; } else { Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { return ip.getHostAddress(); } } } } } catch (Exception e) { System.out.println("获取IP失败!!!!"); } return ""; }
2获取mac
public static String getMacAddress() { try { Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces(); byte[] mac = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface)allNetInterfaces.nextElement(); if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) { continue; } else { mac = netInterface.getHardwareAddress(); if (mac != null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < mac.length; i++) { sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); } if (sb.length() > 0) { return sb.toString(); } } } } } catch (Exception e) { System.out.println(("MAC地址获取失败")); } return ""; }
以上的代码主要解决:有些机器有许多虚拟的网卡,获取IP地址时会出现一些意外,所以需要一些验证:
以上的代码中
netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()
相关文章推荐
- java获取mac地址-屏蔽ip封mac地址
- java获取mac地址-屏蔽ip封mac地址
- java获取本机ip,mac,
- Java获取电脑IP、MAC、各种版本
- java获取mac地址-屏蔽ip封mac地址
- java获取本机ip,mac,os名称,版本等
- Java获取电脑IP、MAC、各种版本
- java服务器端根据ip获取客户端mac地址
- javaWeb快速获取服务器的IP和对应的Mac地址
- java获取mac地址-屏蔽ip封mac地址
- java获取mac地址-屏蔽ip封mac地址
- java获取mac地址-屏蔽ip封mac地址 .
- java程序获取IP、MAC相关地址属性
- Java获取客户端ip mac地址
- java获取mac地址-屏蔽ip封mac地址
- java获取mac地址-屏蔽ip封mac地址
- java获取mac地址-屏蔽ip封mac地址
- java根据本地Ip获取mac地址
- java获取本机ip和mac地址
- 【分享】Java程序获取本机ip,mac,os名称,版本等