我正在使用socket.getaddrinfo
检查主机名是否可解析,捕获socket.gaierror
以检测错误的主机名。这种方法很好,除了在某些系统上,像“12345”这样的字符串被“解析”为垃圾地址。
这里到底发生了什么,我该如何防止它发生?
Python 2.6.6 (r266:84292, Dec 7 2011, 20:48:22)
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> hostname = "12345"
>>> socket.getaddrinfo(hostname, "22", socket.AF_INET, socket.SOCK_STREAM, socket.SOL_TCP)
[(2, 1, 6, '', ('0.0.48.57', 22))]
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> hostname = "12345"
>>> socket.getaddrinfo(hostname, "22", socket.AF_INET, socket.SOCK_STREAM, socket.SOL_TCP)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
答案 0 :(得分:1)
您的字符串将被解析为IP地址。试试hostname="1"
,您会看到它解析为0.0.0.1。这确实很奇怪,手册说:
inet_aton() also accepts strings with less than three dots; see the Unix manual page inet(3) for details.
手册页说这样的字符串是interpreted as a 32-bit value that is stored directly into the binary address without any byte rearrangement.