Question

Can and will an operating system reuse a source port number for a connection to a different destination address/port combination?

If I connect() to enough hosts, and keep those connections open, eventually I'll run out of unique source ports, exhausting the ephemeral range, the non-root range (1025-65,535; assuming non-root) or the absolute range (0-65,535). I want to know if those represent real limits to the number of hosts I can simultaneously have a connection to. I'm interested in what the standards promise (or don't), as well as the reality on Linux (Windows would be a bonus).

I know that opening that many connections will likely run into a number of other limits; that's a different issue and question. If it matters, this massive number of connections would be divided among a similarly large number of processes. I'm interested in the case where I'm requesting an ephemeral port, not manually bind()ing one. If under "normal" circumstances ports won't be reused, are there ways of changing that behavior from user-space (at which point bind()ing to a specific point becomes an option)?

Was it helpful?

Solution

By default, the kernel will not reuse any in-use port for an ephemeral port, which may result in failures if you have 64K+ simultaneous ports in use.

You can explicitly reuse a port by using the SO_REUSEADDR socket option and explicitly binding to the same port. This only works if none of the ports are listening (you can't reuse a listening port), and if you connect each socket to a different remote address.

OTHER TIPS

In theory yes. In practice no, because bind precedes connect, and so it can't see what you're connecting to, so can't see that the 4-tuple would be unique, so won't let you reuse an ephemeral port.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top