gpt4 book ai didi

python - gethostname() 返回准确的主机名,bind() 不喜欢它

转载 作者:行者123 更新时间:2023-12-01 05:11:17 24 4
gpt4 key购买 nike

正在做一个python套接字教程,整个代码库如下

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()

和错误消息:

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

打印主机名给我

super*name*

事实上,这是我的计算机的主机名,尽管我觉得它的末尾应该有“.local”。事实上,如果末尾有 .local,s.bind() 就会起作用。为什么不存在?

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

最佳答案

来自 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.

绑定(bind)套接字的典型方法是使用等效主机规范 '''0.0.0.0' 绑定(bind)到所有网络接口(interface)(对于 IPv4)。这相当于 C 常量 INADDR_ANY:

s.bind(('', port))

然后您就不必担心主机名或当前网络接口(interface)地址等。只有在想要绑定(bind)到特定网络接口(interface)(例如在具有多个 NIC 的主机上)的更不寻常的情况下,您才需要在调用 bind() 时指定地址;在这种情况下,您需要找出所需网络接口(interface)的数字 IP 地址并传递该地址。

关于python - gethostname() 返回准确的主机名,bind() 不喜欢它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24194132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com