Python:如何从FQDN获取IP地址

时间:2011-01-07 15:15:19

标签: python network-programming ip-address

如果我有FQDN,例如www.google.com,我该如何获得相应的IP地址?

3 个答案:

答案 0 :(得分:7)

最简单的方法是socket.gethostbyname()

答案 1 :(得分:3)

您可以使用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中已弃用(并且socket.gethostbyname已使用它实现),因为它不支持IPv6地址,建议使用getaddrinfo

答案 2 :(得分:0)

使用socket.gethostbyname(hostname)请参阅:http://docs.python.org/library/socket.html#socket.gethostbyname