【发布时间】:2011-06-05 08:17:53
【问题描述】:
如果我有一个 FQDN,例如 www.google.com,我如何获得相应的 IP 地址?
【问题讨论】:
标签: python network-programming ip-address
如果我有一个 FQDN,例如 www.google.com,我如何获得相应的 IP 地址?
【问题讨论】:
标签: python network-programming ip-address
最简单的方法是socket.gethostbyname()。
【讨论】:
您可以使用socket.getaddrinfo。这将为您提供与名称关联的不同 IP 地址,还可以为您提供 IPv6 地址。
来自文档:
>>> import socket
>>> help(socket.getaddrinfo)
Help on built-in function getaddrinfo in module _socket:
getaddrinfo(...)
getaddrinfo(host, port [, family, socktype, proto, flags])
-> list of (family, socktype, proto, canonname, sockaddr)
Resolve host and port into addrinfo struct.
>>> from pprint import pprint
>>> pprint(socket.getaddrinfo('www.google.com', 80))
[(2, 1, 6, '', ('74.125.230.83', 80)),
(2, 2, 17, '', ('74.125.230.83', 80)),
(2, 3, 0, '', ('74.125.230.83', 80)),
(2, 1, 6, '', ('74.125.230.80', 80)),
(2, 2, 17, '', ('74.125.230.80', 80)),
(2, 3, 0, '', ('74.125.230.80', 80)),
(2, 1, 6, '', ('74.125.230.81', 80)),
(2, 2, 17, '', ('74.125.230.81', 80)),
(2, 3, 0, '', ('74.125.230.81', 80)),
(2, 1, 6, '', ('74.125.230.84', 80)),
(2, 2, 17, '', ('74.125.230.84', 80)),
(2, 3, 0, '', ('74.125.230.84', 80)),
(2, 1, 6, '', ('74.125.230.82', 80)),
(2, 2, 17, '', ('74.125.230.82', 80)),
(2, 3, 0, '', ('74.125.230.82', 80))]
注意:gethostbyname 在 C 中已被弃用(Python socket.gethostbyname 是用它实现的),因为它不支持 IPv6 地址,建议替换 getaddrinfo。
【讨论】:
使用socket.gethostbyname(hostname) 参见:http://docs.python.org/library/socket.html#socket.gethostbyname
【讨论】: