【问题标题】:How to receive a url from a client and use it with gethostbyname()如何从客户端接收 url 并将其与 gethostbyname() 一起使用
【发布时间】: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') 是一个字符串。

标签: python sockets


【解决方案1】:

尝试对主机进行编码以验证名称解析在服务器端是否正常工作:

socket.gethostbyname('www.google.com')

另外,检查输入的长度以消除任何可能的 '\n'

【讨论】:

  • 这应该是一条评论。
  • 你说得对,它确实有额外的字符。有道理。
  • @Barmar 是的,应该。由于我的声誉低于 50,我无法在上面发表评论。
猜你喜欢
  • 2019-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-23
  • 2015-04-22
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
相关资源
最近更新 更多