【发布时间】:2019-06-06 20:08:00
【问题描述】:
我想通过 python 中的套接字从客户端向服务器发送消息,特别是我会发送一个 url 示例“www.google.com”。然后我只显示IP地址。我使用 telnet 作为我的客户端。所以我输入信息
我尝试了多种方法将消息转换为字符串,但仍未找到解决方案。 “我目前收到此错误:
socket.gaierror: [Errno -2] Name or service not known
Process Process-1:
Traceback (most recent call last):
File "/usr/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/lib/python3.6/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "proxy_server.py", line 44, in handle_connection
host_ip = socket.gethostbyname(str(message.decode('utf-8')))
socket.gaierror: [Errno -2] Name or service not known
不知道如何解决这个问题。当我第一次收到消息而不使用解码时,我应该只使用split() 来删除不需要的东西吗?
# Recieve message from the client
message = conn.recv(2024)
print(message)
print(message.decode('utf-8'))
# host_ip = socket.gethostbyname(message.decode('utf-8'))
host_ip = socket.gethostbyname(str(message.decode('utf-8')))
print(host_ip)
【问题讨论】:
-
请附上完整的错误信息。
-
刚刚添加了完整的错误信息。
-
您获取的是 URL 还是主机名?
www.google.com是主机名,https://www.google.com/search?q=stackoverflow是 URL。 -
您发送到
gethostbyname的确切字符串是什么? (如果您显示所有输出而不仅仅是错误,这会有所帮助。)您不能只向它发送 any 字符串并期望成功。摆脱套接字recv(即用于调试)。只需:import socket; print(socket.gethostbyname("string"))。而且,顺便说一句,message.decode('utf-8')将是一个字符串。