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

164,895

Solution 1

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

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.

Share:
164,895
rob
Author by

rob

Updated on April 07, 2020

Comments

  • rob
    rob about 4 years

    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[]?)

  • rob
    rob about 13 years
    thx! Looks like i skipped this part. sorry for that.
  • Flipbed
    Flipbed over 9 years
    Those who use this please note that if the ip-adress are not valid the timeout for the lookup is long enough that when done repeatedly it causes the program to run slowly.
  • Glenn Maynard
    Glenn Maynard about 9 years
    This is a bad idea if all you're intending to do is parse IP addresses, since getByName will also do hostname lookups. If a hostname is passed to your function, you'll be doing synchronous network I/O where you didn't intend to be.
  • Andris Birkmanis
    Andris Birkmanis over 7 years
    @GlennMaynard: the actual JDK code checks if the first character is a digit, and if yes, then just parses it using IPAddressUtil.
  • Glenn Maynard
    Glenn Maynard over 7 years
    @AndrisBirkmanis But if someone passes in a hostname (eg. because you're parsing a configuration file or similar), that's not what will happen. If you only intend to parse an IP address, then you should use a function that only parses IP addresses.
  • pujan jain
    pujan jain over 6 years
    But this is not giving me as expected one.
  • arulraj.net
    arulraj.net almost 4 years
    IPAddressUtil in sun.net.util is best alternative. But we should be aware of this oracle.com/java/technologies/faq-sun-packages.html