Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getLocalHost() shows wrong IP address

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);
        }
    }
}
like image 664
Atharv Kurdukar Avatar asked Dec 05 '25 15:12

Atharv Kurdukar


1 Answers

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());
    }
 }
like image 156
bl4y. Avatar answered Dec 07 '25 03:12

bl4y.