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

Hrvoje Niksic hniksic at xemacs.org
Tue Feb 26 13:13:18 CET 2008


7stud <bbxx789_05ss at yahoo.com> writes:

> When you surf the Web, say to http://www.google.com, your Web browser
> is a client. The program you contact at Google is a server. When a
> server is run, it sets up business at a certain port, say 80 in the
> Web case. It then waits for clients to contact it. When a client does
> so, the server will usually assign a new port, say 56399, specifically
> for communication with that client, and then resume watching port 80
> for new requests.

Actually the client is the one that allocates a new port.  All
connections to a server remain on the same port, the one it listens
on:

>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.bind(('127.0.0.1', 10000))
>>> s.listen(1)
>>> s.accept()
# now, connect to port 10000 from elsewhere
(<socket._socketobject object at 0xb7adf6f4>, ('127.0.0.1', 36345))
>>> s1 = _[0]
>>> s1
<socket._socketobject object at 0xb7adf6f4>
>>> s1.getsockname()
('127.0.0.1', 10000)        # note the same port, not a different one



More information about the Python-list mailing list