gihooh
gihooh

Reputation: 311

Method getHardwareAddress() gives NullPointerException when using other network's ip

I'm trying to print the Physical address of other computer connected to my network by their ip address.

Using arp -a I can see all networks and their physical address.

But when running a java code I can't retrieve the physical address of it's corresponding ip and it gives me a NullPointerException on the line invoking the getHardwareAddress() method. But If its my computer's ip it gives proper output and no exception is thrown.

Here is what I've got.

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());

}

Upvotes: 2

Views: 3949

Answers (1)

user207421
user207421

Reputation: 310883

You can only get NetworkInterface objects for your own network interfaces, not those of other hosts. See the Javadoc:

It is used to identify the local interface

When you called NetworkInterface.getByInetAddress(add) where add is a foreign IP address, it therefore returned null, which you didn't check for, and so you got a NullPointerException when you used it.

You can't do this.

Upvotes: 2

Related Questions