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

标签 java networking nullpointerexception

我正在尝试通过 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/

相关文章:

python TCP客户端无法连接到我的TCP服务器

c++ - echo 服务器没有响应 udp

java - 测试对象是否为空的通用代码?

Java:将 null 分配给 Boolean 时出现 NullPointerException

java - 如何在jDisktopPane中显示JinternalFrame,但该DisktopPane包含GridLayout?

java - spring 中的构造函数注入(inject)如何促进不变性?

php - 从另一个Docker容器(同一主机,Apache)调用Docker容器中的API

Scala::lazy 值除非打印,否则为 null?

java - Spring Data JPA native 查询中的变量

java - @Produces 方法中 @Mock 的 Junit 4 范围