1

Doing a python socket tutorial, entire codebase is as follows

import socket as so

s = so.socket()

host = so.gethostname()
port = 12345
s.bind((host, port))

s.listen(5)
while True:
    c, addr = s.accept()
    print 'Got connection from', addr
    c.send('Thank you for connecting')
    c.close()

and error message:

Traceback (most recent call last):
  File "server.py", line 13, in <module>
    s.bind((host, port))
  File "/Users/solid*name*/anaconda/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 8] nodename nor servname provided, or not known

Printing hostname gives me

super*name*

Which is, in fact, my computer's hostname, although I feel like there should be '.local' at the end of it. In fact, s.bind() works if there is a .local at the end. Why isn't it there?

Mac OS X 10.7.5, Python 2.7.6 :: Anaconda 2.0.0 (x86_64)

Nils Guillermin
  • 1,867
  • 3
  • 21
  • 51

1 Answers1

2

From the socket module documentation:

If you use a hostname in the host portion of IPv4/v6 socket address, the program may show a nondeterministic behavior, as Python uses the first address returned from the DNS resolution. The socket address will be resolved differently into an actual IPv4/v6 address, depending on the results from DNS resolution and/or the host configuration. For deterministic behavior use a numeric address in host portion.

The typical way of binding sockets is to just bind to all network interfaces, using either of the equivalent host specifications '' or '0.0.0.0' (for IPv4). This is equivalent to the C constant INADDR_ANY:

s.bind(('', port))

And then you don't have to worry about hostnames or current network interface addresses etc. Only in the more unusual case of wanting to bind to a particular network interface (e.g. on a host with multiple NICs) should you ever need to specify the address in the call to bind(); in that case, you need to figure out the numeric IP address of the network interface you want and pass that.

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589