2

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
4

1 回答 1

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.

于 2012-04-11T10:33:42.677 回答