- How to get the IP address of a localhost in Java
- Using the InetAddress class
- Code
- Example 1
- Using the NetworkInterface class
- Example 2
- Getting IP Address and Host Name in Java
- 1.Overview
- 2. InetAddress
- 2.1 Local Server
- 2.2 Remote or Site Server
- 2.3 Methods
- 2.4 Example Programs
- 2.5 Exception
- 3. Processbuilder
- 3.1 Methods
- 3.2 Example program
- 4. NetworkInterface
- 5. Conclusion
- Labels:
- SHARE:
- About Us
- Java 8 Tutorial
- Java Threads Tutorial
- Kotlin Conversions
- Kotlin Programs
- Java Conversions
- Java String API
- Spring Boot
- $show=Java%20Programs
- $show=Kotlin
- JAVA : Get Host Name and IP address of Machine?
- Classes and Methods
- Example
- Output
- Host Name from HttpServletRequest
- Summary
- More Samples
How to get the IP address of a localhost in Java
Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.
This shot covers how to get the IP address A unique address that identifies a device on the internet or a local network. of a local machine/localhost using Java.
Using the InetAddress class
We can use the getLocalHost() static method of the InetAddress class to obtain the localhost IP address.
You must import the java.net package before you can use the InetAddress class, as shown below:
import java.net.InetAddress;
Code
Example 1
import java.net.*;public class Mainpublic static void main(String[] args) throws UnknownHostExceptionInetAddress localHost = InetAddress.getLocalHost();System.out.println(localHost.getHostAddress());>>Using the NetworkInterface class
A computer can have many network interfaces, and each interface can be assigned to multiple IP addresses. The IP address may or may not be reachable outside the machine.
Another approach is as follows:
- Get a list of all the network interfaces using the getNetworkInterfaces() method of the NetworkInterface class.
- For every network interface, loop over all the IP addresses.
- For every IP address, check if it is the local address or not.
Example 2
import java.net.*;import java.util.*;public class Mainpublic static void main(String[] args)tryEnumeration networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();while( networkInterfaceEnumeration.hasMoreElements())for ( InterfaceAddress interfaceAddress : networkInterfaceEnumeration.nextElement().getInterfaceAddresses())if ( interfaceAddress.getAddress().isSiteLocalAddress())System.out.println(interfaceAddress.getAddress().getHostAddress());>> catch (SocketException e)e.printStackTrace();>>>Learn in-demand tech skills in half the time
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.
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.
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 .
InetAddress localAddress = InetAddress.getLocalHost(); String localHostName = localAddress.getHostName(); String localHostAddress = localAddress.getHostAddress(); System.out.println("localHostName : "+localHostName); System.out.println("localHostAddress : "+localHostAddress);localHostName : java-w3schools localHostAddress : 168.0.1.2InetAddress remoteAddress = InetAddress.getByName("google.com"); String remoteHostName = remoteAddress.getHostName(); String remoteHostAddress = remoteAddress.getHostAddress(); System.out.println("remoteHostName : "+remoteHostName); System.out.println("remoteHostAddress : "+remoteHostAddress);remoteHostName : google.com remoteHostAddress : 172.217.163.1422.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.
If takes multiple arguments then need to pass as String[] array or Multiple String arguemnts separated by comma(,).
String[] command = ; 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.
getInputStream(): Returns output of the command in InputStream .
3.2 Example program
Program to get the hostname using ProcessBuilder
ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.command("hostname"); Process process = processBuilder.start();Program to get the ping result of google.com
String [] commands = ; processBuilder.command("ping", "goofle.com"); process = processBuilder.start();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 = 266ms4. 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 .
Labels:
SHARE:
![]()
![]()
![]()
About Us
Java 8 Tutorial
- Java 8 New Features
- Java 8 Examples Programs Before and After Lambda
- Java 8 Lambda Expressions (Complete Guide)
- Java 8 Lambda Expressions Rules and Examples
- Java 8 Accessing Variables from Lambda Expressions
- Java 8 Method References
- Java 8 Functional Interfaces
- Java 8 — Base64
- Java 8 Default and Static Methods In Interfaces
- Java 8 Optional
- Java 8 New Date Time API
- Java 8 — Nashorn JavaScript
Java Threads Tutorial
Kotlin Conversions
Kotlin Programs
Java Conversions
- Java 8 List To Map
- Java 8 String To Date
- Java 8 Array To List
- Java 8 List To Array
- Java 8 Any Primitive To String
- Java 8 Iterable To Stream
- Java 8 Stream To IntStream
- String To Lowercase
- InputStream To File
- Primitive Array To List
- Int To String Conversion
- String To ArrayList
Java String API
- charAt()
- chars() — Java 9
- codePointAt()
- codePointCount()
- codePoints() — Java 9
- compareTo()
- compareToIgnoreCase
- concat()
- contains()
- contentEquals()
- copyValueOf()
- describeConstable() — Java 12
- endsWith()
- equals()
- equalsIgnoreCase()
- format()
- getBytes()
- getChars()
- hashcode()
- indent() — Java 12
- indexOf()
- intern()
- isBlank() — java 11
- isEmpty()
- join()
- lastIndexOf()
- length()
- lines()
- matches()
- offsetByCodePoints()
- regionMatches()
- repeat()
- replaceFirst()
- replace()
- replaceAll()
- resolveConstantDesc()
- split()
- strip(), stripLeading(), stripTrailing()
- substring()
- toCharArray()
- toLowerCase()
- transform() — Java 12
- valueOf()
Spring Boot
$show=Java%20Programs
$show=Kotlin
accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,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,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
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.
JAVA : Get Host Name and IP address of Machine?
Below examples is to get local machine host name and IP address by java api’s. Here also explained about to get host name and IP address by HttpServletRequest.
Classes and Methods
- java.net.InetAddress : class represents an Internet Protocol (IP) address.
- java.net.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.
- java.net.InetAddress.getHostAddress() : Returns the IP address string in textual presentation.
- java.net.InetAddress.getHostName() : Gets the host name for this IP address.
Example
package com.fiot.examples.java.socket; import java.net.InetAddress; public class GetIPAndHostName < public static void main(String[] args) < try < InetAddress inetAddress = InetAddress.getLocalHost(); System.out.println("Local IP Address:- " + inetAddress.getHostAddress()); System.out.println("Local Host Name:- " + inetAddress.getHostName()); >catch(java.net.UnknownHostException ex) < ex.printStackTrace(); >> >Output
Local IP Address:- 192.168.100.27 Local Host Name:- LAPTOP-FacingIssuesOnIT
Host Name from HttpServletRequest
in below example code for web application will get host name from HttpServletRequest.
public void getAppStatus(HttpServletRequest request, HttpServletResponse response) < String hostName=request.getServerName(); try < hostName = InetAddress.getLocalHost().getHostName(); >catch (UnknownHostException e)
Summary
Here we explained about to get host name and ip address of local machine and server machine from HttpServletRequest.
More Samples
For more other JAVA/JDBC sample code follow link JAVA/JDBC Issues.