Does the port change when a server accepts a TCP connection?

The server use the same port to listen and accept new connection, and communicate to the remote client.

Let's me give you an example, (in linux system):

First, start a http server by python:

xiongyu@ubuntu:~$ sudo python -m SimpleHTTPServer 500
Serving HTTP on 0.0.0.0 port 500 ...

Second use nc command to connect to the http server, here we start two client by:

xiongyu@ubuntu:~$ nc 0.0.0.0 500

Use netstat to see the netstate of port 500:

xiongyu@ubuntu:~$ netstat -natp |grep ':500'
tcp    0      0 0.0.0.0:500         0.0.0.0:*          LISTEN      54661/python
tcp    0      0 127.0.0.1:51586     127.0.0.1:500      ESTABLISHED 57078/nc
tcp    0      0 127.0.0.1:51584     127.0.0.1:500      ESTABLISHED 54542/nc
tcp    0      0 127.0.0.1:500       127.0.0.1:51586    ESTABLISHED -
tcp    0      0 127.0.0.1:500       127.0.0.1:51584    ESTABLISHED 54661/python

You can see, the http server use port 500 to LISTEN for the client, after a new client connected to the server, it still use the port 500 to communite with the client, but with a new file descriptor .


The socket associated with the new descriptor returned by accept on the server will use the same port on the server side of the connection as the original socket (assuming "normal" definitions where the client initiates the connection). The new socket will have a different client port number (the remote port from the server's point of view).


The new socket is an application-level concept introduced because each established connection needs a unique file descriptor (also distinct from the listening file descriptor), which maps to, but isn't the same as, a TCP session. The session itself is identified by the combination of source and destination address and port. The source (client) port is usually chosen at random, while the destination (server) port is the listen port. No additional port is allocated.