Python Socket Programming - Actual Remote Port

Nowadays, I do network programming in Python and want to confirm the flow, which, it seems to me, occurs between the client and server:

  • Servers listen on the advertised port (9999)
  • The client connects to the server, creating a new socket (for example, 1111).
  • The servers accept the client’s request and automatically generate a new socket (????), which will now handle the communication between the client and the server.

As you can see, there are 3 sockets in the stream above:

  • Server socket that listens for clients
  • Client-created socket
  • The socket created by the server to process the client

I know that I need to get ports for the first two sockets (9999 and 1111), but I don’t know how to get a “real” port that interacts with the client on the server side. The snippet I'm using right now:

def sock_request(t):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('localhost', 9999))
    print('local sock name: ' + str(s.getsockname()))
    print('peer sock name: ' + str(s.getpeername()))
    s.send('a' * 1024 * int(t))
    s.close()

Any help on getting the “port” number on the server that really communicates with the client would be greatly appreciated. TIA.

+3
source share
1 answer

The new socket is on the same port. A TCP connection is identified by four pieces of information: the source IP address and port, as well as the IP address and destination port. So the fact that your server has two sockets on the same port (i.e., a Listening socket and a received socket) is not a problem.

+4
source

All Articles