getLocalAddress() returning 0.0.0.0
java, sockets, udp
Solution
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.
Problem
I am trying to write a program using Sockets and I need to get my own local IP address. When I use getLocalAddress in the socket, I only get 0.0.0.0. Here is a little piece of my code: ``` DatagramSocket socket; DatagramPacket pacoteEnvio = new DatagramPacket(msgByte, msgByte.length, addr, 6500); socket = new DatagramSocket(); System.out.println("Local address = " + socket.getLocalAddress()); socket.send(pacoteEnvio); ``` Do you have any idea? I am using UDP, so I am not sure if I can get my IP this way because it's connectionless, but I think you can help me!