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

Thomas Bellman bellman at lysator.liu.se
Mon Feb 25 12:56:25 EST 2008


7stud <bbxx789_05ss 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?

The answer is that the server *doesn't* change its port.  As you
could see in the output of your server, the socket that accept()
returned also had local port 5052.  Each *client* will however
get a unique local port at *its* end.

A TCP connection is identified by a four-tuple:

    ( localaddr, localport, remoteaddr, remoteport )

Note that what is local and what is remote is relative to which
process you are looking from.  If the four-tuple for a specific
TCP connection is ( 127.0.0.1, 5052, 127.0.0.1, 50816 ) in your
server, it will be ( 127.0.0.1, 50816, 127.0.0.1, 5052 ) in the
client for the very same TCP connection.

Since your client hasn't bound its socket to a specific port, the
kernel will chose a local port for you when you do a connect().
The chosen port will be more or less random, but it will make
sure that the four-tuple identifying the TCP connection will be
unique.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"There are many causes worth dying for, but  !  bellman @ lysator.liu.se
 none worth killing for."         -- Gandhi  !  Make Love -- Nicht Wahr!



More information about the Python-list mailing list