获取IP并排除本地回路.
private static String getIpAddress() throws Exception {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
List<String> ipList = new ArrayList<>(8);
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> iNetAddresses = networkInterface.getInetAddresses();
while (iNetAddresses.hasMoreElements()) {
InetAddress inetAddress = iNetAddresses.nextElement();
if (inetAddress instanceof Inet4Address) {
if (!"127.0.0.1".equals(inetAddress.getHostAddress())) {
ipList.add(inetAddress.getHostAddress());
}
}
}
}
return ipList.toString();
}
获取MAC地址,与网卡(包括虚拟网卡)个数相关
private static String getMac() throws Exception {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
StringBuilder sb = new StringBuilder();
ArrayList<String> tmpList = new ArrayList<>(8);
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
for (InterfaceAddress interfaceAddress : interfaceAddresses) {
InetAddress inetAddress = interfaceAddress.getAddress();
NetworkInterface network = NetworkInterface.getByInetAddress(inetAddress);
if (network == null) {
continue;
}
byte[] mac = network.getHardwareAddress();
if (mac == null || mac.length == 0) {
continue;
}
sb.delete(0, sb.length());
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
tmpList.add(sb.toString());
}
}
//去重
Set<String> set = new HashSet<>(tmpList);
return new ArrayList<>(set).toString();
}
测试结果:
与系统的ipconfig -all比较
linux上进行测试:
放着 以后备用 嘻嘻