我socket.getaddrinfo
用来检查主机名是否可解析,socket.gaierror
以检测错误的主机名。这很好用,除了在某些系统上,诸如“12345”之类的字符串被“解析”为垃圾地址。
这里到底发生了什么,我该如何防止它发生?
Python 2.6.6 + CentOS 6.2 上的奇怪行为
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 + OS X 10.6 上的预期行为
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