Pages

Wednesday, November 18, 2020

Getting IP Address and Host Name in Java

1.Overview

In this quick tutorial, We'll learn how to get IP address in java for the current server. As well will learn how to get Host Name of local machine using Java API methods.

We mainly focus how these can be achieved using classes such as InetAddress, Processbuilder and NetworkInterface in this tutorial.

Getting IP Address and Host Name in Java

2. InetAddress


Class InetAddress is present in package java.net.InetAddress. This class deals IP address and host name of the current machine.

An instance of an InetAddress consists of an IP address and possibly its corresponding host name.

InetAddress class deals with local host and remote host using getLocalHost() and getByName​(String host) respectively.

2.1 Local Server

Creating instance of InetAddress for local server that mean where java program is running.

InetAddress address = InetAddress.getLocalHost();


Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress .

Note: The resolved address may be cached for a short period of time.

2.2 Remote or Site Server

Creating instance of InetAddress for site server that mean where java program is not running. In other words, retrieving the ip address for other server which not for the current host.

InetAddress address = InetAddress.getByName("remote-host.com");

getByName name method takes String as argument which is remote host name.

getByName() method determines the IP address of a host, given the host's name.

2.3 Methods


All the following methods are static methods hence no need of object creation for InetAddress class.

InetAddress.getLocalHost(): Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.

InetAddress.getHostAddress(): Returns the IP address string in textual presentation.

InetAddress.getHostName(): Gets the host name for this IP address.

2.4 Example Programs

Let us take a look at the code to get the IP Address and Host Name using InetAddress.

getLocalHost:

InetAddress localAddress = InetAddress.getLocalHost();
String localHostName = localAddress.getHostName();
String localHostAddress = localAddress.getHostAddress();

System.out.println("localHostName : "+localHostName);
System.out.println("localHostAddress : "+localHostAddress);

Output:

localHostName : java-w3schools
localHostAddress : 168.0.1.2

getByName:

InetAddress remoteAddress = InetAddress.getByName("google.com");

String remoteHostName = remoteAddress.getHostName();
String remoteHostAddress = remoteAddress.getHostAddress();

System.out.println("remoteHostName : "+remoteHostName);
System.out.println("remoteHostAddress : "+remoteHostAddress);

Output:

remoteHostName : google.com
remoteHostAddress : 172.217.163.142

2.5 Exception

InetAddress throws the following exceptions.

UnknownHostException in both cases if the local or site host name could not be resolved into an address.

SecurityException is thrown if the we do not have sufficient access to execute this and any security violation.

3. Processbuilder

Processbuilder is in package java.lang.Processbuilder. This class deals with operating system processes creation.

This works with both windows and unix enviornments.

ProcessBuilder instance takes command as input which is called as Attribute.

3.1 Methods

command(String...): This method takes String var-args as argument. Accept operating system commands. If only one command then need to pass as string.

pb.command("hostname");

If takes multiple arguments then need to pass as String[] array or Multiple String arguemnts separated by comma(,).

pb.command("ping", "google.com");

OR

String[] command = {"ping", "google.com"};
pb.command(command);

start(): start method creates sub-process. This method can be called multiple times. For each invocation, a new sub process will be created under operating system. Excutes the given command.

pb.start()

getInputStream(): Returns output of the command in InputStream.


pb.getInputStream()

3.2 Example program

Program to get the hostname using ProcessBuilder

ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("hostname");
Process process = processBuilder.start();

Output:

java-w3schools-host-name

Program to get the ping result of google.com

String [] commands = {"ping", "goofle.com"};
processBuilder.command("ping", "goofle.com");
process = processBuilder.start();

Output:

Pinging goofle.com [192.185.39.34] with 32 bytes of data:
Reply from 192.185.39.34: bytes=32 time=264ms TTL=41
Reply from 192.185.39.34: bytes=32 time=268ms TTL=41
Reply from 192.185.39.34: bytes=32 time=264ms TTL=41
Reply from 192.185.39.34: bytes=32 time=271ms TTL=41

Ping statistics for 192.185.39.34:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 264ms, Maximum = 271ms, Average = 266ms

4. NetworkInterface


This class represents a Network Interface made up of a name, and a list of IP addresses assigned to this interface. It is used to identify the local interface on which a multicast group is joined. Interfaces are normally known by names such as "le0".

Enumeration e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
 NetworkInterface n = (NetworkInterface) e.nextElement();
 Enumeration ee = n.getInetAddresses();
 while (ee.hasMoreElements()) {
  InetAddress i = (InetAddress) ee.nextElement();
  System.out.println("HostName : " + i.getHostName() + ", IP Address : " + i.getHostAddress());
 }
}

5. Conclusion


In this tutorial, We've seen how to get the IP Address and HostName in different ways using Java API.

Further discussed about each way

A. By using InetAddress, We can retrieve the Host Name and IP address for local and remote server. InetAddress is available from Java 1.0
B. ProcessBuilder provides ability to run the direct operating system dependent commands from Java.
C. NetworkInterface provides access to all servers information under same domain.

All codes shown are shown in this post are available on GitHub.

How to get client ip address in servlet application from HTTP header?

No comments:

Post a Comment

Please do not add any spam links in the comments section.