geniusburger
geniusburger

Reputation: 428

How to Bind to the same UDP port on multiple interfaces

I have two network interfaces and am trying to bind to the same UDP port on both of them but I get an error when I try to bind to the second one, EADDRINUSE. When I bind to the sockets I pass a sockaddr* where I've setup the port and the unique IP address to use.

Do I have to use the socket option SO_REUSEADDR? Will this allow messages to be received on either socket or will they go to the socket that matches the IP address their bound to?

Upvotes: 2

Views: 3352

Answers (1)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84151

You can bind(2) one socket to INADDR_ANY for IPv4 or to in6addr_any for IPv6 (you don't have to, but that's the usual approach). That will make that single socket able to accept packets from all network interfaces on the box.

Then SO_REUSEADDR socket option will allow you to bind other sockets to more specific addresses, i.e. to individual interfaces, and same port.

Packets will be received on the socket that is bound to the address best matching the destination IP address of a given packet.

Upvotes: 3

Related Questions