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

Roy Smith roy at panix.com
Tue Feb 26 00:00:11 EST 2008


In article 
<e4138617-bb4b-4f59-ab78-a49104854d83 at 60g2000hsy.googlegroups.com>,
 7stud <bbxx789_05ss at yahoo.com> wrote:

> But your claim that the server doesn't change its port flies in the
> face of every description I've read about TCP connections and
> accept().  The articles and books I've read all claim that the server
> port 5053 is a 'listening' port only.  Thereafter, when a client sends
> a request for a connection to the listening port, the accept() call on
> the server creates a new socket for communication between the client
> and server, and then the server goes back to listening on the original
> socket.

You're confusing "port" and "socket".

A port is an external thing.  It exists in the minds and hearts of packets 
on the network, and in the RFCs which define the TCP protocol (UDP too, but 
let's keep this simple).

A socket is an internal thing.  It is a programming abstraction.  Sockets 
can exist that aren't bound to ports, and several different sockets can be 
bound to the same port.  Just like there can be multiple file descriptors 
which are connected to a given file on disk.

The TCP protocol defines a state machine which determines what packets 
should be sent in response when certain kinds of packets get received.  The 
protocol doesn't say how this state machine should be implemented (or even 
demands that it be implemented at all).  It only requires that a TCP host 
behave in a way which the state machine defines.

In reality, whatever operating system you're running on almost certainly 
implements in the kernel a state machine as described by TCP.  That state 
machine has two sides.  On the outside is the network interface, which 
receives and transmits packets.  On the inside is the socket interface to 
user-mode applications.  The socket is just the API by which a user program 
interacts with the kernel to get it to do the desired things on the network 
interface(s).

Now, what the articles and books say is that there is a listening SOCKET.  
And when you accept a connection on that socket (i.e. a TCP three-way 
handshake is consummated on the network), the way the socket API deals with 
that is to generate a NEW socket (via the accept system call).  There 
really isn't any physical object that either socket represents.  They're 
both just programming abstractions.

Does that help?



More information about the Python-list mailing list