【发布时间】:2015-07-20 00:37:17
【问题描述】:
我正在关注这个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
尽管网络良好,但我收到此错误:
>>> 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
我该如何解决这个问题?
【问题讨论】:
-
host的值是多少?socket.gethostname()是否有可能返回无效的主机名? -
如果您尝试:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)会发生什么?如果这不起作用,请尝试更改host = ''? -
@shuttle87 应该这样做。我试图找到我的套接字代码,但
.AF_INET是我们以前使用过的——我认为这会起作用! -
主机有效,返回机器名。我做了 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM), s 是一个有效的套接字对象,但得到了同样的错误。 host = '' 有效,但为什么它有效,因为根据 python 文档,如果使用 AF_INET,它应该是主机名字符串或 IP 地址?