Reputation: 2571
I am following this example,
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
and I am getting this error despite good network:
>>> s.bind((host, port))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Applications/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
How can I fix this?
Upvotes: 0
Views: 11037
Reputation: 13052
Let's take a look at the docs:
socket.gethostname()
Return a string containing the hostname of the machine where the Python interpreter is currently executing.
If you want to know the current machine’s IP address, you may want to use gethostbyname(gethostname()). This operation assumes that there is a valid address-to-host mapping for the host, and the assumption does not always hold.
Note: gethostname() doesn’t always return the fully qualified domain name; use getfqdn() (see above).
I guess this is what's happening: bind is trying to establish IP address for the host, but it fails. Run host = socket.gethostbyname(socket.gethostname())
and instead of a valid IP address you'll most probably see the same error as when calling bind.
You say the returned hostname is valid, but you have to make sure it's recognised by the DNS responder. Does the resolution work when doing, for example, ping {hostname}
from the command line?
Possible solutions would be:
host = socket.getfqdn()
(in case you were not getting the fully qualified name which then couldn't be resolved properly). Even if it works I think you should try and fix the local resolution.host = ''
), which on bind would mean "listen on all available interfaces". (This is the first example in the docs.)Upvotes: 3