The easiest way I know is to use NetworkInterface.getNetworkInterfaces()
and the linked Javadoc notes that you can use getNetworkInterfaces()
+getInetAddresses()
to obtain all IP addresses for this node. That might look something like
try {
Enumeration<NetworkInterface> nics = NetworkInterface
.getNetworkInterfaces();
while (nics.hasMoreElements()) {
NetworkInterface nic = nics.nextElement();
Enumeration<InetAddress> addrs = nic.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress addr = addrs.nextElement();
System.out.printf("%s %s%n", nic.getName(),
addr.getHostAddress());
}
}
} catch (SocketException e) {
e.printStackTrace();
}
and I get (for my network)
wlan0 192.168.2.9
lo 127.0.0.1
if you don't want to display loop-back you can test the NetworkInterface
with isLoopback()
.
while (nics.hasMoreElements()) {
NetworkInterface nic = nics.nextElement();
if (!nic.isLoopback()) {
// ... as before
}
}