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

7stud bbxx789_05ss at yahoo.com
Mon Feb 25 07:17:16 EST 2008


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.








More information about the Python-list mailing list