Given the server code:
import socket
HOST = 'localhost'
PORT = 65200
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
c, addr = s.accept()
with c:
client_addr = c.getsockname()[0]
client_port = c.getsockname()[1]
print('Connected to client address: {} port: {}'.format(client_addr, client_port))
And given the client code:
import socket
connections = {}
SRC_HOST = 'localhost'
SRC_PORT = 65300
# Create 5 connections
for i in range(5):
connections[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connections[i].bind((HOST, SRC_PORT + i))
DEST_HOST = 'localhost'
DEST_PORT = 65200
# For each connection, send one message
for s in connections.keys():
connections[s].connect((DEST_HOST, DEST_PORT))
connections[s].sendall(b'Hello world!')
# Close active connections
for s in connections.keys():
connections[s].close()
In the output of the server code, why does the port of socket object c remain 65200 for each connected client?
Connected to client address: 127.0.0.1 port: 65200
Connected to client address: 127.0.0.1 port: 65200
Connected to client address: 127.0.0.1 port: 65200
Connected to client address: 127.0.0.1 port: 65200
Connected to client address: 127.0.0.1 port: 65200
Per Python docs on sockets, socket.accept() shall return (c, addr) where c is a new socket object for each new connection retrieved from the listen queue.
Am I wrong in assuming a new socket object requires a unique port? If so, how would the server code differentiate in between the 5 different connected clients if the port is 65200 for all of them?
In other words, what if I wanted to only send client (localhost, 65302) something in response and not the other connected clients?