Reputation: 135
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);
}
}
}
Upvotes: 3
Views: 4756
Reputation: 60046
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
Upvotes: 0
Reputation: 540
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());
}
}
Upvotes: 5