How to determine IP Address & hostname of Local Computer in Java



Problem Description

How to determine IP Address & hostname of Local Computer?

Solution

Following example shows how to find local IP Address & Hostname of the system using getLocalAddress() method of InetAddress class.

import java.net.InetAddress;

public class Main {
   public static void main(String[] args) throws Exception {
      InetAddress addr = InetAddress.getLocalHost();
      System.out.println("Local HostAddress: "+addr.getHostAddress());
      String hostname = addr.getHostName();
      System.out.println("Local host name: "+hostname);
   }
}

Result

The above code sample will produce the following result.

Local HostAddress: 192.168.1.4
Local host name: harsh
java_networking.htm
Advertisements