简体   繁体   中英

Get all IP addresses associated with a host

I'm trying to write some code that can get all the IP addresses associated with a given hostname.

This is what I have so far:

def getips(hostname):
    try:
        result = socket.getaddrinfo(hostname, None, socket.AF_INET,\
            socket.SOCK_DGRAM, socket.IPPROTO_IP, socket.AI_CANONNAME)
        list = [x[4][0] for x in result]
        return list
    except Exception, err:
        print "error"
    return ""


ips = getips('bbc.co.uk')                                                   

print ips

The problem is, sometimes it returns all 4 IPs associated with the specific host in this example, sometimes it returns just one. Is there any way to do this in Python so it consistently returns all the IPs associated with a host?

getaddrinfo() calls the resolver library on your host to lookup IP addresses for any given host. There is no special magic in python that can force it to get a different set of results than what the resolver shows.

For eg if you run strace on your python script, you will notice that the resolver is invoked:

open("/lib/x86_64-linux-gnu/libresolv.so.2", O_RDONLY|O_CLOEXEC) = 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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