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);
}
}
}
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With