host.py 文件源码

python
阅读 21 收藏 0 点赞 0 评论 0

项目:NFStest 作者: thombashi 项目源码 文件源码
def get_ip_address(host='', ipv6=False):
        """Get IP address associated with the given host name.
           This could be run as an instance or class method.
        """
        if len(host) != 0:
            ipstr = "v6" if ipv6 else "v4"
            family = socket.AF_INET6 if ipv6 else socket.AF_INET
            try:
                infolist = socket.getaddrinfo(host, 2049, 0, 0, socket.SOL_TCP)
            except Exception:
                infolist = []
            for info in infolist:
                # Ignore loopback addresses
                if info[0] == family and info[4][0] not in ('127.0.0.1', '::1'):
                    return info[4][0]
            raise Exception("Unable to get IP%s address for host '%s'" % (ipstr, host))
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            if ipv6:
                s.connect(("2001:4860:4860::8888", 53))
            else:
                s.connect(("8.8.8.8", 53))
            ip = s.getsockname()[0]
            s.close()
            return ip
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号