Reputation: 64195
I read some socket programming sample code from here. And one question suddenly hits me.
It takes a 4-tuple to construct a TCP socket connection:
<client address, client port, server address, server port>
But it seems only the <server address, server port>
is explicitly specified in both client and server code. And this server port
is only used for listening, not the one actually used by server for communicating.
So who decide the <client address, client port>
? And why not explicitly by the programmer of client code?
Correction, seems the bold part above is incorrect. The server port don't change. Ref: Does the port change when a TCP connection is accepted by a server?
Upvotes: 1
Views: 709
Reputation: 310874
So who decide the
{client address, client port}
?
TCP/IP. It figures out which IP address has the best route to the target, and finds you a free port.
And why not explicitly by the programmer of client code?
You can specify it if you like via bind()
before connect()
, but there is rarely any need to do so.
And this server port is only used for listening, not the one actually used by server for communicating.
That's not correct. Listening and communicating to accepted connections uses the same port number.
Upvotes: 2
Reputation: 919
These client ports are called ephemeral ports, this is explained fairly well here:
https://en.wikipedia.org/wiki/Ephemeral_port
And perhaps better here:
http://www.ncftp.com/ncftpd/doc/misc/ephemeral_ports.html
What is not immediately evident is that when a connection is established that the client side of the connection uses a port number. Unless a client program explicitly requests a specific port number, the port number used is an ephemeral port number. Ephemeral ports are temporary ports assigned by a machine's IP stack, and are assigned from a designated range of ports for this purpose. When the connection terminates, the ephemeral port is available for reuse, although most IP stacks won't reuse that port number until the entire pool of ephemeral ports have been used. So, if the client program reconnects, it will be assigned a different ephemeral port number for its side of the new connection.
Upvotes: 3