How would I get a users IP address?
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
System.out.println("Current IP address : " + ip.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
That returns: 127.0.0.1
I know that is not my IP. It is my local IP address. How do I get a users IP using java..?
The shortest method is:
However
getLocalHostdocs say:and in some cases
InetAddress.getLocalHost()doesn’t consult your interfaces, it simply returns constant 127.0.0.1 (for IPv4))I think
NetworkInterface.getNetworkInterfacesis what you need to enumerate all the possibilities. Here’s an example which doesn’t show virtual addresses, but works for “main” interfaces:Alternatively:
Try using this (First output should be IP after PC name):
References: