有了我在这里找到的所有可能的解决方案以及其他答复,我将为我的解决方案做出贡献。您需要使用包含“ ip”或“ mac”的字符串来指定参数,具体取决于您要检查的内容。如果计算机没有接口,则它将返回一个包含null的字符串,否则将返回一个包含您要求的字符串(ip地址或mac)。
如何使用它:
System.out.println("Ip: " + GetNetworkAddress.GetAddress("ip"));
System.out.println("Mac: " + GetNetworkAddress.GetAddress("mac"));
结果(如果计算机有网卡):
Ip: 192.168.0.10
Mac: 0D-73-ED-0A-27-44
结果(如果计算机没有网卡):
Ip: null
Mac: null
这是代码:
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
public class GetNetworkAddress {
public static String GetAddress(String addressType) {
String address = "";
InetAddress lanIp = null;
try {
String ipAddress = null;
Enumeration net = null;
net = NetworkInterface.getNetworkInterfaces();
while (net.hasMoreElements()) {
NetworkInterface element = net.nextElement();
Enumeration addresses = element.getInetAddresses();
while (addresses.hasMoreElements() && element.getHardwareAddress().length > 0 && !isVMMac(element.getHardwareAddress())) {
InetAddress ip = addresses.nextElement();
if (ip instanceof Inet4Address) {
if (ip.isSiteLocalAddress()) {
ipAddress = ip.getHostAddress();
lanIp = InetAddress.getByName(ipAddress);
}
}
}
}
if (lanIp == null)
return null;
if (addressType.equals("ip")) {
address = lanIp.toString().replaceAll("^/+", "");
} else if (addressType.equals("mac")) {
address = getMacAddress(lanIp);
} else {
throw new Exception("Specify \"ip\" or \"mac\"");
}
} catch (UnknownHostException ex) {
ex.printStackTrace();
} catch (SocketException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return address;
}
private static String getMacAddress(InetAddress ip) {
String address = null;
try {
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
address = sb.toString();
} catch (SocketException ex) {
ex.printStackTrace();
}
return address;
}
private static boolean isVMMac(byte[] mac) {
if(null == mac) return false;
byte invalidMacs[][] = {
{0x00, 0x05, 0x69}, //VMWare
{0x00, 0x1C, 0x14}, //VMWare
{0x00, 0x0C, 0x29}, //VMWare
{0x00, 0x50, 0x56}, //VMWare
{0x08, 0x00, 0x27}, //Virtualbox
{0x0A, 0x00, 0x27}, //Virtualbox
{0x00, 0x03, (byte)0xFF}, //Virtual-PC
{0x00, 0x15, 0x5D} //Hyper-V
};
for (byte[] invalid: invalidMacs){
if (invalid[0] == mac[0] && invalid[1] == mac[1] && invalid[2] == mac[2]) return true;
}
return false;
}
感谢@mateuscb 如何在Java中确定Internet网络接口帖子,不幸的是之前没有对该帖子进行任何支持,但他为此次更新做出了贡献。
改进了跳过虚拟机网卡的方法(最受欢迎的VM软件)