Search code examples
javadnsinetaddress

How do I check if InetAddress was created using a hostname or an IP address?


I would like to know that if an InetAddress object was initialized with a hostname or an IP address at construction. Is there a way to check that in java?


Solution

  • Yes, you can.

    The InetAddress.toString() returns string representation in following format: host-name/IP address. If host name is unknown (that happens when the instance was created using IP address) the first part is empty.

    The following code fragment:

        System.out.println(InetAddress.getByName("localhost").toString());
        System.out.println(InetAddress.getByName("127.0.0.1").toString());
        System.out.println(InetAddress.getByName("www.google.com").toString());
        System.out.println(InetAddress.getByName("173.194.113.145").toString());
    

    Prints this output:

    localhost/127.0.0.1
    /127.0.0.1
    www.google.com/173.194.113.144
    /173.194.113.145
    

    So, you can say the following:

    public static boolean isCreatedFromIp(InetAddress addr) {
        return addr.toString().startsWith("/");
    }
    

    EDIT: I have not checked this with IPv6, however I believe similar solution exists because toString() implementation does not depend on the IP version.