sockets, gethostname() changing

Steve Holden steve at holdenweb.com
Fri May 25 00:24:27 EDT 2007


7stud wrote:
> Hi,
> 
> I'm experimenting with a basic socket program(from a book), and both
> the client and server programs are on my computer.   In both programs,
> I call socket.gethostname(), but I discovered that when I am connected
> to the internet, both the client and server hang and nothing happens.
> I discovered that the hostname of my computer automatically changes to
> that of my isp when I'm connected to the internet, and presumably the
> server program on my computer cannot listen on my isp's address(host,
> port).   Is there a way to make the hostname of my computer static, so
> that it doesn't change to my isp's hostname when I connect to the
> internet.  I'm using mac os 10.4.7.  Why does my computer's hostname
> dynamically change in the first place?
> 
> server program:
> -------------------
> import socket
> 
> s = socket.socket()
> 
> host = socket.gethostname()
> print host
> port = 1274
> 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()
> 
> 
> client program:
> -------------------
> import socket
> 
> s = socket.socket()
> 
> host = socket.gethostname()
> port = 1274
> 
> s.connect((host, port))
> print s.recv(1024)
> s.close()
> 
For local testing it is *much* easier to have your client and server use 
IP address 127.0.0.1 - this is the usual address on the "loopback" 
network, which doesn't require any physical network hardware to operate.

Just as a matter of interest, what is socket.gethostname() returning? I 
suspect it will depend on whether you have established an interface 
specific domain suffix - I haven't, and I have no trouble with your code.

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