gpt4 book ai didi

java - 方法 getHardwareAddress() 在使用其他网络的 ip 时给出 NullPointerException

转载 作者:行者123 更新时间:2023-11-30 09:11:55 26 4
gpt4 key购买 nike

我正在尝试通过 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 - 方法 getHardwareAddress() 在使用其他网络的 ip 时给出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21869054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com