Prabhu. S
Prabhu. S

Reputation: 1793

What are the use cases of SO_REUSEADDR?

I have used SO_REUSEADDR to have my server which got terminated to restart without complaining that the socket is already in use. I was wondering: are there other uses of SO_REUSEADDR? Has anyone used the socket option for other than said purpose?

Upvotes: 27

Views: 37024

Answers (3)

Brian R. Bondy
Brian R. Bondy

Reputation: 347226

For TCP, the primary purpose is to restart a closed/killed process on the same address.

The flag is needed because the port goes into a TIME_WAIT state to ensure all data is transferred.

If two sockets are bound to the same interface and port, and they are members of the same multicast group, data will be delivered to both sockets.

I guess an alternative use would be a security attack to try to intercept data.

(Source)


For UDP, SO_REUSEADDR is used for multicast.

More than one process may bind to the same SOCK_DGRAM UDP port if the bind() is preceded by:

int one = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));

In this case, every incoming multicast or broadcast UDP datagram destined to the shared port is delivered to all sockets bound to the port.

(Source)

Upvotes: 45

hack03er
hack03er

Reputation: 11

For the answer for TCP see @brian-r-bondy 's answer. But for UDP

const int enable = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == -1) {
  perror("setsockopt");
  exit(EXIT_FAILURE);
}

can have different effects:

  1. for Unicast the datagram will "never [be] delivered to more than one socket, regardless of how many sockets are bound to the datagram's destination port" [0] and "only the latest opened socket can see any incoming packets" [1]
  2. for "every incoming multicast or broadcast UDP datagram destined to the shared port is delivered to all sockets bound to the port" [0] but for this you have to do an additional setup

[0: http://www.kohala.com/start/mcast.api.txt]

[1: http://ossasepia.com/2021/12/14/the-half-life-of-udp-sockets-or-reuseaddr/]

Upvotes: 1

dwc
dwc

Reputation: 24890

The other main use is to allow multiple sockets to bind() to the same port on UDP. You might not think that would come up, but sometimes multiple apps may want to listen on broadcast/multicast addresses with a given port number. It also allows one to bind to the wildcard address, while also binding to a specific address. For instance, Apache might bind to *:80 and 10.11.12.13:80

Upvotes: 11

Related Questions