Java: Convert a String (representing an IP) to InetAddress

JavaIpInetaddress

Java Problem Overview


> Possible Duplicate:
> Is there an easy way to convert String to Inetaddress in Java?

I'm trying to convert a string(representing an IP address, e.g. 10.0.2.50) into an InetAddress obj.

According to the API it is possible to create an Object providing a String representing a hostname (e.g. www.google.ch). This is not an option for me since I do not have the hostname for each InetAddress object I want to create(besides that it takes too long).

Is it possible to convert a String (e.g. 10.0.2.50) into an InetAddress obj.? (according to the api it is possible to do so if you have the IP as byte[], but how do I convert a String containing an IP into byte[]?)

Java Solutions


Solution 1 - Java

Simply call InetAddress.getByName(String host) passing in your textual IP address.

From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.

InetAddress javadoc

Solution 2 - Java

From the documentation of InetAddress.getByName(String host):

> The host name can either be a machine > name, such as "java.sun.com", or a > textual representation of its IP > address. If a literal IP address is > supplied, only the validity of the > address format is checked.

So you can use it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrobView Question on Stackoverflow
Solution 1 - JavaJustin WaughView Answer on Stackoverflow
Solution 2 - JavaBjörnView Answer on Stackoverflow