Getting the local address using mechanisms like this generally doesn't work in the way you expect. A system generally has at least two addresses - 127.0.0.1
and ip address of nic
, when you bind to an address for listening, you are binding to INADDR_ANY, which is the same as the address 0.0.0.0
which is the same as binding to 127.0.0.1
and ip address of nic
. Consider a laptop with a wired and wireless network card - either or both of them could be connected at the same time. Which would be considered the IP address of the system in this case?
I stole a subset of the answer for enumerating the ip addresses of all enabled NIC cards, which deals with the addresses of all the NICs, which lists the IP addresses for all the interfaces, on my system I have 10 interfaces, so I end up with a lot of IP addresses.
try {
System.out.println("Full list of Network Interfaces:");
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
System.out.println(" " + intf.getName() + " " + intf.getDisplayName());
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
System.out.println(" " + enumIpAddr.nextElement().toString());
}
}
} catch (SocketException e) {
System.out.println(" (error retrieving network interface list)");
}
Generally, though if you're server programming, when you receive a packet on a UDP service, it contains the sender's IP address, which you simply send the response to, and the computer is smart enough to send it out of the correct network interface.