Is there an easy way to convert String to Inetaddress in Java?

Viewed 21452

I am trying to convert strings into Inetaddress. I am not trying to resolve hostnames: the strings are ipv4 addresses. Does InetAddress.getByName(String host) work? Or do I have to manually parse it?

5 Answers

Yes, that will work. The API is very clear on this ("The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address."), and of course you could easily check yourself.

Beware: it seems that parsing an invalid address such as InetAddress.getByName("999.999.999.999") will not result in an exception as one might expect from the documentation's phrase:

the validity of the address format is checked

Empirically, I find myself getting an InetAddress instance with the local machine's raw IP address and the invalid IP address as the host name. Certainly this was not what I expected!

Related