98

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

Community
  • 1
  • 1
rob
  • 2,904
  • 5
  • 25
  • 38

2 Answers2

186

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.

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Justin Waugh
  • 3,975
  • 1
  • 21
  • 14
  • thx! Looks like i skipped this part. sorry for that. – rob Apr 06 '11 at 19:45
  • 2
    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. – Flipbed Dec 17 '14 at 13:19
  • 42
    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. – Glenn Maynard Mar 25 '15 at 17:00
  • 9
    @GlennMaynard: the actual JDK code checks if the first character is a digit, and if yes, then just parses it using IPAddressUtil. – Andris Birkmanis Oct 20 '16 at 20:57
  • 1
    @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. – Glenn Maynard Nov 04 '16 at 22:28
  • But this is not giving me as expected one. – pujan jain Dec 19 '17 at 09:38
  • 1
    `IPAddressUtil` in sun.net.util is best alternative. But we should be aware of this https://www.oracle.com/java/technologies/faq-sun-packages.html – arulraj.net Jul 21 '20 at 00:34
19

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.

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Björn
  • 29,019
  • 9
  • 65
  • 81