Reputation: 1438
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?
Upvotes: 0
Views: 1604
Reputation: 115388
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.
Upvotes: 4