简体   繁体   中英

Socket programming in Python — actual remote port

I've been doing a bit of network programming these days in Python and would like to confirm the flow I think happens between the client and the server:

  • The servers listens to a given advertised port (9999)
  • The client connects to the server by creating a new socket (eg 1111)
  • The servers accepts the client request and automatically spawns a new socket (????) which would now handle the communication between the client and the server

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

  • The server socket which listens to clients
  • The socket spawned by the client
  • The socket spawned by the server to handle client

I'm aware of getting the ports for the first two sockets (9999 and 1111) but don't know how to get the "real" port which communicates with the client on the server side.The snippet I'm using right now is:

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 which actually communicates with the client would be much appreciated. TIA.

The new socket is on the same port. A TCP connection is identified by 4 pieces of information: the source IP and port, and the destination IP and port. So the fact that your server has two sockets on the same port (ie the listening socket and the accepted socket) is not a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM