gpt4 book ai didi

python - 错误 : nodename nor servname provided, 或未知(python 套接字)

转载 作者:行者123 更新时间:2023-11-28 17:13:34 25 4
gpt4 key购买 nike

我正在尝试通过本教程学习如何使用套接字:
https://www.tutorialspoint.com/python/python_networking.htm
我已将网站上的代码复制到我的目录中,并完全按照教程中的方式运行它,但出现了错误。这是教程中的代码。

#!/usr/bin/python           # This is server.py file

import socket # Import socket module

s = socket.socket() # Create a socket object
host = 'localhost' # 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("asdf")
c.send('Thank you for connecting')
c.close() # Close the connection

和client.py

#!/usr/bin/python           # This is client.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.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done

这些是我运行的控制台命令:

python server.py &
python client.py

运行命令后出现以下错误:

Traceback (most recent call last):
File "client.py", line 9, in <module>
s.connect((host, port))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/soc ket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 8] nodename nor servname provided, or not known

如果这有帮助,我使用的 python 版本是 Python 2.7.10,我使用的 mac 版本是 10.12.6

提前致谢

最佳答案

来自 socket.gethostname 的文档:

Return a string containing the hostname of the machine where the Python interpreter is currently executing.

Note: gethostname() doesn’t always return the fully qualified domain name; use getfqdn() for that.

主机 IP 与主机名不同。您有几个选择:

  1. 您可以手动将 host 分配给 0.0.0.0localhost

  2. 也可以查询socket.gethostbyname :

    host = socket.gethostbyname(socket.gethostname()) # or socket.getfqdn() if the former doesn't work

关于python - 错误 : nodename nor servname provided, 或未知(python 套接字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45747730/

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