Page 1 of 1

UDP socket confusion with multiple addresses

Posted: Tue Aug 09, 2016 11:23 am
by mariuszp
I am confused about how UDP sockets can function when there are multiple IP addresses in the system.

Suppose there are 3 addresses on the system: 10.0.1.1, 10.0.2.1, 10.0.3.1. I bind a UDP socket to INADDR_ANY, so it should receive datagrams directed to EITHER of those 3 addresses, right?

So now suppose the hsot 2.0.1.1 send a datagram to 10.0.2.1, and the host 2.0.1.2 sends a datagram to 10.0.3.1. Both expect a response. How is the system supposed to know which address to respond from when sending a datagram back to 2.0.1.1 and which one when sending a datagram to 2.0.1.2? If it simply uses the default address (say 10.0.1.1), then each of those hosts would be receiving the response from a different address than they expect.

Though in IPv4 we typically have only 1 address, there are usually multiple in IPv6 so this is an obviously practical problem.

Re: UDP socket confusion with multiple addresses

Posted: Tue Aug 09, 2016 11:52 am
by Kazinsal
UDP sockets bound with INADDR_ANY bind to the default interface address when sending datagrams.

Re: UDP socket confusion with multiple addresses

Posted: Tue Aug 09, 2016 11:57 am
by mariuszp
And when said datagram is sent, do they REMAIN bound to the default interface address, or do they continue to listen on all addresses?

Re: UDP socket confusion with multiple addresses

Posted: Tue Aug 09, 2016 12:04 pm
by Kazinsal
Bad phrasing on my part, sorry. Your socket's bind never changes. The socket will remain bound to INADDR_ANY, and any program that tries to bind to that UDP port will get an unkind slap in the face. You can continue to receive messages to that port on any configured IP address on that UDP port through that socket.