2

I am trying to execute following code. I am new to Java, so this is my first time in java.net. There is no error in program, but I am getting localhost address as 192.168.56.1 whereas my IP is 192.168.2.10

import java.net.*;
class InetAddressDemo
{
    public static void main(String[] args)
    {
        try
        {
            InetAddress address = InetAddress.getLocalHost();
            System.out.println("\nLocalhost Address : " + address + "\n");
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
    }
}
Atharv Kurdukar
  • 115
  • 2
  • 12
  • you can find a good explanation here about that http://stackoverflow.com/questions/9481865/getting-the-ip-address-of-the-current-machine-using-java – Youcef LAIDANI Mar 18 '17 at 14:01

2 Answers2

4

You should enumerate network interfaces, since you may have multiple interfaces. getLocalHost() returns only the loopback address of your machine.

Enumeration Interfaces = NetworkInterface.getNetworkInterfaces();
while(Interfaces.hasMoreElements())
{
    NetworkInterface Interface = (NetworkInterface)Interfaces.nextElement();
    Enumeration Addresses = Interface.getInetAddresses();
    while(Addresses.hasMoreElements())
    {
        InetAddress Address = (InetAddress)Addresses.nextElement();
        System.out.println(Address.getHostAddress());
    }
 }
bl4y.
  • 530
  • 1
  • 3
  • 10
0

A short answer, to get the IP Address that you already mention in your question you have to use :

String address = InetAddress.getLocalHost().getHostAddress();

You can find a good explanation about that here : Getting the IP address of the current machine using Java

Community
  • 1
  • 1
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140