How to check if an IP address is the local host on a multi-homed system?

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)