Sunday, 24 April 2016

How do I get the IP address and hostname of a machine ?


Get the IP address of a machine from its hostname
The InetAddress class is able to resolve IP addresses for you.
Call getHostAddress() method of InetAddress, which returns a string in the xxx.xxx.xxx.xxx address form.

InetAddress inet = 
             InetAddress.getByName("http://www.davidreilly.com");

System.out.println ("IP: " + inet.getHostAddress());


Find out the current IP address for my machine
The InetAddress has a static method called getLocalHost() which will return the current address of the local machine.
You can then use the getHostAddress() method to get the IP address.

InetAddress local = InetAddress.getLocalHost();

System.out.println ("Local IP: " + local.getHostAddress());


Get the hostname of a machine from its IP address
The InetAddress class contains a method that can return the domain name of an IP address.
You need to obtain an InetAddress class, and then call its getHostName() method.
This will return the hostname for that IP address.
Depending on the platform, a partial or a fully qualified hostname may be returned.

InetAddress inet = InetAddress.getByName("209.204.220.121");

System.out.println ("Host: " + inet.getHostName());

No comments:

Post a Comment

Note: only a member of this blog may post a comment.