When a client connects to a server using TCP, a new socket is created for the TCP stream. Does the connection remain on the same port the connection was made or does it get changed to some other port?
A TCP connection has two ends and permits communication in both directions. Each end's sending port is the other end's receiving port. That is always the case. If you're asking if each end's sending port can be the same as the other end's receiving port, the answer is yes.
Applications are designed to use either the UDP or TCP transport layer protocol depending on the type of connection they require. For example a web server normally uses TCP port 80.
The TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) protocols mainly use the port numbers. A port number is a unique identifier used with an IP address. A port is a 16-bit unsigned integer, and the total number of ports available in the TCP/IP model is 65,535 ports.
TCP and UDP ports are not related to each other. TCP ports are interpreted by the TCP stack, while the UDP stack interprets UDP ports. Ports are a way of multiplexing the connection so that multiple devices can connect to a node.
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.
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With