Get all IPs associated with a URL, Python

2019-08-10 21:53发布

I am trying to find all the IPs that are associated with a URL. I have been using the package "socket" but am confused by the varying amount of IPs returned with different functions. For example see below. Is there a function to return all the IPs?

socket.gethostbyname('google.com')
#returns 1 ip

socket.gethostbyname_ex('google.com')
#returns 6 ips

socket.getaddrinfo('google.com', 80)
#returns 12 ips

Is there a function to return all the IPs?

标签: python
1条回答
Animai°情兽
2楼-- · 2019-08-10 22:05

No, there is no function to return "all" IPs. The IP addresses that you see are what your local DNS server knows for google.com. These addresses vary from location to location.

All of the methods behave differently, for a reason

  • gethostbyname returns 1 of the IPv4 addresses in the A records of this host. This is for the simple stuff of "let's just connect any address that is google.com".

  • gethostbyname_ex returns all known IPv4 addresses; that is, all the addresses from A records for google.com. This is for the case that you need high availability, so you can try to connect several of these IPv4 addresses and proceed with the connection that succeeds.

  • Since neither of the above support IPv6 addresses, socket.getaddrinfo returns them as well. Unless you also provide argument proto=socket.IPPROTO_TCP, you will have some extra protocols, like same address repeated 3 times - for TCP, UDP and RAW sockets for example.

Of these 3, socket.getaddrinfo gives the "most" of the IP addresses, but due to distributed nature of DNS and google's DNS especially, there is no way that you can get them all.

查看更多
登录 后发表回答