从用户输入获取主机时无法解析主机IP地址

时间:2019-07-16 21:44:24

标签: python python-2.7 sockets input

所以我正在使用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

1 个答案:

答案 0 :(得分:0)

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

感谢Thierry Lathuille在评论中提供答案。 https://stackoverflow.com/users/550094/thierry-lathuille

相关问题