【问题标题】:How do I get a website's IP address using Python 3.x?如何使用 Python 3.x 获取网站的 IP 地址?
【发布时间】:2011-06-16 10:47:19
【问题描述】:

我有一个代表域名的字符串。如何使用 Python 3.x 获取对应的 IP 地址?像这样的:

>>> get_ip('http://www.stackoverflow.com')
'64.34.119.12'

【问题讨论】:

标签: python dns ip


【解决方案1】:
Python 3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Intel)] on win32
>>> import socket
>>> socket.gethostbyname('cool-rr.com')
'174.120.139.162'

注意:

  • gethostbyname() 不适用于IPv6
  • gethostbyname() 使用 C 调用 gethostbanme(),已弃用。

如果这些有问题,请改用 socket.getaddrinfo()。

【讨论】:

    【解决方案2】:
    >>> import socket
    
    >>> def get_ips_for_host(host):
            try:
                ips = socket.gethostbyname_ex(host)
            except socket.gaierror:
                ips=[]
            return ips
    
    >>> ips = get_ips_for_host('www.google.com')
    >>> print(repr(ips))
    ('www.l.google.com', [], ['74.125.77.104', '74.125.77.147', '74.125.77.99'])
    

    【讨论】:

      【解决方案3】:

      最简单的方法是使用socket.gethostbyname()。但是,这不支持 IPv6,并且基于已弃用的 C 调用 gethostbanme()。如果你关心这些问题,你可以改用更通用的socket.getaddrinfo()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-05
        • 2018-07-20
        • 1970-01-01
        相关资源
        最近更新 更多