我正在尝试使用本教程学习如何使用套接字:
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,我使用的是10.12.6版本的mac
提前致谢
答案 0 :(得分:2)
来自socket.gethostname
的文档:
返回一个字符串,其中包含机器的主机名 Python解释器目前正在执行。
注意:
gethostname()
并不总是返回完全限定的域 名称;请使用getfqdn()
。
主机IP与主机名不同。你有几个选择:
您可以手动将host
分配给0.0.0.0
或localhost
您还可以查询socket.gethostbyname
:
host = socket.gethostbyname(socket.gethostname()) # or socket.getfqdn() if the former doesn't work
答案 1 :(得分:0)
我对您的代码进行了一些更改。这是 server.py
#!/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)
c,addr= s.accept()
print "Got connection from the ", addr
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))
msg = (s.recv(1024))
print msg
s.close # Close the socket when done
我希望它会有所帮助