sockets, gethostname() changing

Steve Holden steve at holdenweb.com
Fri May 25 13:06:53 EDT 2007


7stud wrote:
[...]
> 
> The strange thing is: the hostname and port in the output are not what
> I'm using in my server program:
> ---------
> import socket
> 
> s = socket.socket()
> 
> print "made changes 2"
> 
> host = socket.gethostname()  #I'm not connected to the internet when I
> use this line
> print host
> 
> port = 1291
> s.bind((host, port))
> 
> s.listen(5)
> while("Ctrl-C hasn't been entered"):
>     c, addr = s.accept()  #blocks and waits for client connection
>     print "Got socket connection from", addr
>     c.send("Thank you for connecting.  Now get lost.")
>     c.close()
> ----------
> 
> The full output of that program is:
> 
> made changes 2
> my-names-computer.local
> Got socket connection from ('127.0.0.1', 49222)
> 
> The hostname now appears to be permanently stuck as "127.0.0.1", and
> the port is wrong. That output was so confusing to me, I wasn't even
> sure whether the file I was editing was actually the file that was
> executing, so I printed out "made changes #" at the top of the file to
> make sure the file I was editing was the one that was actually
> executing.
> 
> I can't remember exactly what the output was for addr before I started
> messing around with the HOSTNAME in /etc/config, but I'm pretty sure
> addr contained the same hostname as the line above it in the output,
> and the port matched the port in the program.
> 
> Any ideas why the hostname and port in the last line of the output are
> not the same as the ones used in the program anymore?
> 
Because the client is using what's called an "ephemeral" port - it is 
getting an arbitrary port number from the TCP layer, guaranteed to be 
unused by any other socket, and using that to connect to your server 
socket. Remember a connection has two ends - the details you are 
printing out from your server are those of the client endpoint.

If you run several clients simultaneously you will find that each uses a 
different port number. That's exactly what's needed to make sure that 
the protocol stack can deliver the right information to the right client.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
------------------ Asciimercial ---------------------
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.com        squidoo.com/pythonology
tagged items:         del.icio.us/steve.holden/python
All these services currently offer free registration!
-------------- Thank You for Reading ----------------




More information about the Python-list mailing list