Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 218
rob Avatar asked Apr 06 '11 19:04

rob


People also ask

How to convert string IP to InetAddress?

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.

Which method returns a string that represents the host name associated with the InetAddress object?

The getHostName() method returns a String that contains the name of the host with the IP address represented by this InetAddress object.

How would you convert an IP address into a hostname in Java?

In Java, you can use InetAddress. getLocalHost() to get the Ip Address of the current Server running the Java app and InetAddress. getHostName() to get Hostname of the current Server name.

How do I convert a string into an Internet address?

in_addr_t inet_addr(const char *strptr) This function call converts the specified string in the Internet standard dot notation to an integer value suitable for use as an Internet address. The converted address will be in Network Byte Order (bytes ordered from left to right).


2 Answers

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

like image 181
Justin Waugh Avatar answered Sep 16 '22 15:09

Justin Waugh


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.

like image 44
Björn Avatar answered Sep 16 '22 15:09

Björn