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) {
e.printStackTrace();
}

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.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s