$show=/label

Getting IP Address and Host Name in Java

SHARE:

A Quick Guide to How to get IP Address in Java and How to get Host Name in Java for local and remote server. Explaned with Example Programs to get Local Server IP Address in windows and Unix.

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.


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,72,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,2,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,48,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Softwares,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,8,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Getting IP Address and Host Name in Java
Getting IP Address and Host Name in Java
A Quick Guide to How to get IP Address in Java and How to get Host Name in Java for local and remote server. Explaned with Example Programs to get Local Server IP Address in windows and Unix.
https://3.bp.blogspot.com/-4ZwXBbZFu5E/XOP34xsihSI/AAAAAAAABiQ/SKEtN9DYDBsS5GVFJ7t9kxUa5CpdtmNjQCLcBGAs/s320/Getting%2BIP%2BAddress%2Band%2BHost%2BName%2Bin%2BJava.PNG
https://3.bp.blogspot.com/-4ZwXBbZFu5E/XOP34xsihSI/AAAAAAAABiQ/SKEtN9DYDBsS5GVFJ7t9kxUa5CpdtmNjQCLcBGAs/s72-c/Getting%2BIP%2BAddress%2Band%2BHost%2BName%2Bin%2BJava.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/05/get-ip-address-hostname.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/05/get-ip-address-hostname.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content