Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating InetAddress object in Java

Tags:

java

ip

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

InetAddress API documentation

like image 494
yotamoo Avatar asked Apr 19 '11 16:04

yotamoo


People also ask

How are the instances of InetAddress class created?

The InetAddress class doesn't have public constructors, so you create a new instance by using one of its factory methods: getByName(String host): creates an InetAddress object based on the provided hostname.

What is the use of InetAddress class in Java?

Class InetAddress. This class represents an Internet Protocol (IP) address. An IP address is either a 32-bit or 128-bit unsigned number used by IP, a lower-level protocol on which protocols like UDP and TCP are built.

What is use of InetAddress getByName () function?

The getByName() method of InetAddress class determines the IP address of a host from the given host's name. If the host name is null, then an InetAddress representing an address of the loopback interface is returned.


1 Answers

You should be able to use getByName or getByAddress.

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address

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

The method that takes a byte array can be used like this:

byte[] ipAddr = new byte[]{127, 0, 0, 1}; InetAddress addr = InetAddress.getByAddress(ipAddr); 
like image 133
Bala R Avatar answered Oct 12 '22 20:10

Bala R