Creating an InetAddress Object in Java

I am trying to convert the address indicated by an IP number or name, both in String (i.e. localhost and 127.0.0.1 ), into an InetAdress object. There is no constructor, but rather static methods that return InetAddress. Therefore, if I get the host name, this is not a problem, but what if I get the IP number? There is one method that receives byte [], but I'm not sure how this can help me. All other methods get the host name.

InetAddress API Documentation

+60
java ip
Apr 19 '11 at 16:15
source share
5 answers

You should be able to use getByName or getByAddress.

The host name can be a machine name, for example "java.sun.com", or a text representation of its IP address

 InetAddress addr = InetAddress.getByName("127.0.0.1"); 

A method that accepts a byte array can be used as follows:

 byte[] ipAddr = new byte[]{127, 0, 0, 1}; InetAddress addr = InetAddress.getByAddress(ipAddr); 
+107
Apr 19 '11 at 16:24
source share

From the API for InetAddress

The host name can be a machine name, for example "java.sun.com", or a textual representation of its IP address. If the literal IP address is provided only the validity period of the address format.

+6
Apr 19 '11 at 16:21
source share
 ip = InetAddress.getByAddress(new byte[] { (byte)192, (byte)168, (byte)0, (byte)102} ); 
+4
May 15 '16 at 12:07
source share

InetAddress.getByName also works for ip address.

From JavaDoc

The host name can be a machine name, for example "java.sun.com", or a textual representation of its IP address. If the literal IP address is provided only the validity period of the address format.

+3
Apr 19 '11 at 16:24
source share

Api is pretty easy to use.

 // Lookup the dns, if the ip exists. if (!ip.isEmpty()) { InetAddress inetAddress = InetAddress.getByName(ip); dns = inetAddress.getCanonicalHostName(); } 
+3
Apr 19 '11 at 16:27
source share



All Articles