Java: Convert a String (representing an IP) to InetAddress [duplicate]
Asked Answered
G

2

101

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

Gerrygerrymander answered 6/4, 2011 at 19:15 Comment(1)
Didn't find this one, it is indeed the same problem.Gerrygerrymander
J
190

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.

Janeljanela answered 6/4, 2011 at 19:21 Comment(8)
thx! Looks like i skipped this part. sorry for that.Gerrygerrymander
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.Bibliography
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.Combustor
@GlennMaynard: the actual JDK code checks if the first character is a digit, and if yes, then just parses it using IPAddressUtil.Burdened
@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.Combustor
But this is not giving me as expected one.Merideth
IPAddressUtil in sun.net.util is best alternative. But we should be aware of this oracle.com/java/technologies/faq-sun-packages.htmlLamented
@GlennMaynard what is the alterntaive then?Fluorocarbon
Z
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.

Zygote answered 6/4, 2011 at 19:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.