SO_REUSEADDR and SO_REUSEPORT are related but have different behaviors and use cases.
-
SO_REUSEADDR allows multiple sockets to bind to the same address and port combination provided they each have the option set. The key use of this option is to allow a socket to bind to a port which remains in the TIME_WAIT state after the previous connection was closed. This is commonly used by servers to allow immediate restarts without waiting for the TIME_WAIT state of TCP to expire.
-
SO_REUSEPORT (which originated in BSD systems and was later added to Linux with slightly different semantics) allows multiple sockets to listen on the same IP address and port as long as all instances have the SO_REUSEPORT option set. This feature is useful for load balancing traffic across multiple processes or threads within the same host. It's most commonly used with datagram (UDP) sockets but also works with stream (TCP) sockets.
When you enable SO_REUSEPORT:
- Each socket must explicitly set this option before binding to the address.
- The kernel will balance incoming connections across the multiple listening sockets (for TCP) or distribute datagram packets (for UDP) among them, providing a way to achieve parallelism for accepting connections or reading packets.
- It improves performance by allowing a multithreaded or multi-process server to create a separate listening socket for each child and have the kernel distribute incoming connections across them.
In contrast, when you enable SO_REUSEADDR:
- It's typically intended to avoid waiting for the
TIME_WAIT state to expire when a listening socket is closed and then quickly reopened, allowing the reuse of the same port without issues.
- It does not distribute incoming connections or datagrams across multiple sockets as
SO_REUSEPORT does.
On systems where both options are available, they serve different purposes and can be used independently. If SO_REUSEPORT suits your needs (e.g., for load balancing), you might not need SO_REUSEADDR. However, if you want to ensure that you can quickly restart a server without issues relating to the TIME_WAIT state but don't need load balancing, then SO_REUSEADDR is what you're looking for.
On Linux, both TCP and UDP have the SO_REUSEPORT option, which has an additional behavior beyond SO_REUSEADDR. For instance, it allows for a level of redundancy as if one process crashes, other processes can still handle requests on the same port.
But you should note that you typically wouldn't set both SO_REUSEADDR and SO_REUSEPORT on the same socket. You'd choose the one that fits your particular use case:
- Use
SO_REUSEADDR for the common case where you just want to ensure a server can be restarted quickly.
- Use
SO_REUSEPORT if you need to spread incoming connections or datagram packets across multiple sockets/processes for load balancing or redundancy reasons.
Always refer to the man pages (man 7 socket for Linux, man setsockopt for BSD) for the most accurate and system-specific information.