41

For a machine with multiple NIC cards, is there a convenient method in Java that tells whether a given IP address is the current machine or not. e.g.

boolean IsThisMyIpAddress("192.168.220.25");
MItch Branting
  • 613
  • 1
  • 6
  • 6

1 Answers1

73

If you are looking for any IP address that is valid for the local host then you must check for special local host (e.g. 127.0.0.1) addresses as well as the ones assigned to any interfaces. For instance...

public static boolean isThisMyIpAddress(InetAddress addr) {
    // Check if the address is a valid special local or loop back
    if (addr.isAnyLocalAddress() || addr.isLoopbackAddress())
        return true; // Was local sub-net.

    // Check if the Non-local address is defined on any Local-interface.
    try {
        return NetworkInterface.getByInetAddress(addr) != null;
    } catch (SocketException e) {
        return false;
    }
}

With a string, indicating the port, call this with:

boolean isMyDesiredIp = false;
try
{
    isMyDesiredIp = isThisMyIpAddress(InetAddress.getByName("192.168.220.25")); //"localhost" for localhost
}
catch(UnknownHostException unknownHost)
{
    unknownHost.printStackTrace();
}
Top-Master
  • 7,611
  • 5
  • 39
  • 71
Kevin Brock
  • 8,874
  • 1
  • 33
  • 37
  • That should be InetAddress.getHostName("ip comes here") ... getbyHostName does not exist. – Abhijeet Kashnia Jan 31 '12 at 09:42
  • 3
    @AbhijeetKashnia: Thanks, but actually it should be `InetAddress.getByName()`, `getHostName()` is an object method, not a class method and it does something different (it gets the host name for the IP address, such as using a reverse DNS lookup). – Kevin Brock Jan 31 '12 at 11:01