network programming: how does s.accept() work?

7stud bbxx789_05ss at yahoo.com
Mon Feb 25 07:28:56 EST 2008


On Feb 25, 5:17 am, 7stud <bbxx789_0... at yahoo.com> wrote:
> On Feb 25, 4:08 am, 7stud <bbxx789_0... at yahoo.com> wrote:
>
>
>
> > The question I'm really trying to answer is: if a client connects to a
> > host at a specific port, but the server changes the port when it
> > creates a new socket with accept(), how does data sent by the client
> > arrive at the correct port?  Won't the client be sending data to the
> > original port e.g. port 5052 in the client code above?
>
> If I change the clients to this:
>
> import socket
> import time
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>
> host = 'localhost'
> port = 5052  #server port
>
> print s.getsockname()  #<------------NEW LINE
> s.connect((host, port))
> print s.getsockname()
>
> response = []
> while 1:
>     piece = s.recv(1024)
>     if piece == '':
>         break
>
>     response.append(piece)
>
> Then I get output from the clients like this:
>
> ('0.0.0.0', 0)
> ('127.0.0.1', 51439)
>
> ('0.0.0.0', 0)
> ('127.0.0.1', 51440)
>
> The server port 5052(i.e. the one used in connect()) is not listed
> there. That output indicates that the client socket is initially
> created with some place holder values, i.e. 0.0.0.0, 0.  Then accept()
> apparently sends a message back to the client that in effect says,
> "Hey, in the future send me data on port 51439."  Then the client
> fills in that port along with the ip address in its socket object.
> Thereafter, any data sent using that socket is sent to that port and
> that ip address.

Implicit in that description is that the client must get assigned a
port number before the call to connect(), or maybe the call to
connect() assigns a port number to the client.  In any case, the
server has to receive both the client's ip address and port number as
part of the client's request for a connection in order for the server
to know where to send the response.  The server then uses that ip
address and port number to send back a message to the client that
tells the client what port number future communications need to be
sent to.



More information about the Python-list mailing list