Obtaining a local address using such mechanisms usually does not work as you expect. Usually the system has at least two addresses - 127.0.0.1
and ip address of nic
, when you bind to the listening address, you bind to INADDR_ANY, which matches the address 0.0.0.0
, which matches the binding to 127.0.0.1
and ip address of nic
. Consider a laptop with a wired and wireless network card - either one or both of them can be connected at the same time. What will be considered the IP address of the system in this case?
I stole a subset of the answer for listing the IP addresses of all allowed NICs , which looks at the addresses of all network adapters that list the IP addresses for all interfaces on my system, I have 10 interfaces, so I get 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)"); }
Typically, though, if you program the server when you receive the packet in the UDP service, it contains the IP address of the sender to which you simply send the response, and the computer is smart enough to send it from the correct network interface.
source share