Java: Convert a String (representing an IP) to InetAddress
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.
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.
rob
Updated on April 07, 2020Comments
-
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 anInetAddress
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 anInetAddress
obj.? (according to the api it is possible to do so if you have the IP asbyte[]
, but how do I convert aString
containing an IP intobyte[]
?) -
rob about 13 yearsthx! Looks like i skipped this part. sorry for that.
-
Flipbed over 9 yearsThose 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 about 9 yearsThis 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 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 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 over 6 yearsBut this is not giving me as expected one.
-
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