【问题标题】:Failing to resolve host IP address when taken from user input从用户输入获取时无法解析主机 IP 地址
【发布时间】:2019-11-25 16:43:12
【问题描述】:

所以我正在使用 python 中的套接字侦听器,当我将主机 IP 作为用户输入,而不是作为预定义的字符串时,它无法打开连接并显示下面包含的错误消息。当我将主机 IP 作为预定义变量直接放入代码中时,它可以正常工作。我想这是因为所有用户输入末尾都包含换行符。我想问一下之前是否有人遇到过这个问题,是否有任何方法可以过滤掉用户输入末尾的换行符。

代码:

import socket
target_host = raw_input("Please enter a host IP\n")
target_port = *Some Port*
command = "hostname"
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host, target_port))

错误:

    client.connect((target_host, target_port))
File "C:\Python27\lib\socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 11001] getaddrinfo failed

【问题讨论】:

  • print target_host 并发布输出?
  • target_host = target_host.strip() 将删除字符串两端的任何换行符和空格。附带说明:尽管 Python 2.7 将在 2020 年 1 月正式结束生命周期,但您是否有充分的理由继续使用它?
  • 感谢您的帮助。我会尝试脱衣舞。使用 2.7 不完全是我的选择
  • Strip 修复了它。谢谢。

标签: python python-2.7 sockets input


【解决方案1】:

使用 .strip() 解决了这个问题。

感谢 Thierry Lathuille 在 cmets 中的回答。 https://stackoverflow.com/users/550094/thierry-lathuille

【讨论】:

    猜你喜欢
    • 2013-01-29
    • 2011-01-10
    • 1970-01-01
    • 2012-05-31
    • 2021-01-04
    • 2013-03-25
    • 2018-08-26
    • 2011-03-12
    相关资源
    最近更新 更多