Sockets and Port Numbers
Hosts may have multiple resources they want to consume, and servers may have multiple service they want to expose for consumption. TCP provides a connection between endpoints which represent consumer and service. These are identified by 16-bit integers, TCP Port Numbers and these are the fundamental abstractions on which TCP is based. These end-points are often called sockets.

If I want to access a web server, my PC selects a random port number as the source port; in the case above, I use port 12,345. Most ports under 1024 have been preassigned to well-known services. In this case it selects port 80 for http and makes a connection. Simultaneously my PC wants to bring up a secure web session to the same server, from a different programme.

In this case, my PC selects a new source port number, 12,346 and accesses the web server on its port 443. A TCP connection is a pair of endpoints, so multiple PCs can access this server on port 80 and 443 simultaneously and a given TCP port number on a server can shared by many clients. The combination of IP address and port number give a unique 48 bit mapping for each service. Port numbers are assigned in various ways, based on three ranges.
System Ports (0-1023) of which 0-256 are called well-known ports
User Ports (1024-49151)
Dynamic and/or Private Ports (49152-65535) The IANA maintains a registry of assigned ports.
In Python, from the client side, I connect to the port on the server. The source port will be random.
s.connect((TCP_IP, TCP_PORT))
On the server, I bind to the port I'm listening on.
s.bind((TCP_IP, TCP_PORT))
print(f'Bound to {TCP_IP}:{TCP_PORT}')
while True:
s.listen(1)
conn, addr = s.accept()
Last updated