我正在尝试通过 IP 地址打印连接到我的网络的其他计算机的物理地址。
使用arp -a
我可以看到所有网络及其物理地址。
但是,当运行 java 代码时,我无法检索其对应 ip 的物理地址,并且在调用 getHardwareAddress()
方法时,它给了我一个 NullPointerException
异常。但如果它是我的计算机的 IP,它会给出正确的输出并且不会引发异常。
这是我得到的。
public void printMacAddress() throws UnknownHostException, SocketException {
String ipAddress = "192.168.0.105";
byte[] mac = null;
InetAddress add = InetAddress.getByName(ipAddress);
NetworkInterface network = NetworkInterface.getByInetAddress(add);
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) ? "-" : ""));
}
System.out.print("The mac address is : ");
System.out.println(sb.toString());
}
最佳答案
您只能获取您自己的网络接口(interface)的 NetworkInterface
对象,而不能获取其他主机的网络接口(interface)的对象。请参阅Javadoc :
It is used to identify the local interface
当您调用 NetworkInterface.getByInetAddress(add)
时,其中 add
是外部 IP 地址,因此它返回 null,
而您没有这样做。 t 检查,因此在使用它时出现了 NullPointerException
。
你不能这样做。
关于java - 使用其他网络的 ip 时,方法 getHardwareAddress() 给出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21869054/