简体   繁体   English

Python:如何从FQDN获取IP地址

[英]Python: How do I get the IP address from a FQDN

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

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

You can use socket.getaddrinfo . 您可以使用socket.getaddrinfo That will give you the differents IP address associated with the name, and can also give you the IPv6 address. 这将为您提供与名称关联的不同IP地址,还可以为您提供IPv6地址。

From the documentation: 从文档:

>>> 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))]

Note: gethostbyname is deprecated in C (and Python socket.gethostbyname is implemented with it) as it does not support IPv6 addresses, and getaddrinfo is the recommended replacement. 注意:在C中不推荐使用gethostbyname (并且使用它实现了socket.gethostbyname ),因为它不支持IPv6地址,建议使用getaddrinfo

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM