I have a program which requires it to know it's IP Address. However when I use
InetAddress current_addr = addresses.nextElement();
It returns
127.0.1.1
Which isn't very helpful. How can I get my non-local IP Address from java?
I have a program which requires it to know it's IP Address. However when I use
InetAddress current_addr = addresses.nextElement();
It returns
127.0.1.1
Which isn't very helpful. How can I get my non-local IP Address from java?
What do you get when you use:
InetAddress IP = InetAddress.getLocalHost();
String ipAddress = IP.getHostAddress();
it should ideally give you the ip address if you don't have more than one network interfaces.
I tested it locally and it gives me proper ip address of my machine i.e.
192.168.2.10
If you have more than one network interface then you can try to use the NetworkInterface class, here is the sample:
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
for (; n.hasMoreElements();)
{
NetworkInterface e = n.nextElement();
System.out.println("Interface: " + e.getName());
Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements();)
{
InetAddress addr = a.nextElement();
System.out.println(" " + addr.getHostAddress());
}
}
Source taken from a related post: java InetAddress.getLocalHost(); returns 127.0.0.1 ... how to get REAL IP?