2

I wrote this code for finding google ip in python

import socket
print socket.gethostbyname('google.com')
.
.
173.194.39.0

but if we use command prompt and ping command for finding google ip result is:216.58.208.36 why there is difference between two results?

shahram555
  • 23
  • 2
  • check out this question http://stackoverflow.com/questions/13309560/socket-getfqdn-and-socket-gethostname-are-giving-different-ip-addresses-when – Mazdak Jan 03 '15 at 19:50

2 Answers2

3

Both of those IP addresses resolve to Google.com. We can verify this from the command line with the unix whois command.

$ whois 216.58.208.36 

NetRange:       216.58.192.0 - 216.58.223.255
CIDR:           216.58.192.0/19
NetName:        GOOGLE

$ whois 173.194.39.0

NetRange:       173.194.0.0 - 173.194.255.255
CIDR:           173.194.0.0/16
NetName:        GOOGLE

I ran into this same issue and the cause was that the first command that required an IP address was using a cached DNS entry (because the DNS entry's time to live (TTL) hadn't expired yet) and then by the time the second command was issued the TTL had expired on the cached entry so a new DNS request was made for the domain therefore grabbing a new IP address from the DNS server which happened to be different because the domain had a lot of IP addresses just like Google.com.

Python just relies on the Operating System's DNS resolver (or whatever daemon is running) and as far as I know the socket module doesn't give you the ability to clear the DNS cache before it tries to resolve an address. If you want more control over this functionality you can use DNSPython or something similar. If you are using a daemon for DNS on your operating system (like on Linux, for example) then usually restarting the daemon will force a flush of DNS cache and you find both addresses to the be same (unless you run into the timing issue as described above with the TTL's expiring).

Max Worg
  • 2,932
  • 2
  • 20
  • 35
1

Hostnames are translated to IP addresses through something called a DNS server. When you type a name into a web browser or use a program such as ping, the hostname that you provide (google.com) eventually reaches an authoritative DNS server for that domain-separate from the server that you correspond with for the actual content.

google.com has multiple different servers that can respond to data requests. Depending on the implementation of the different programs you are using to generate the request and other factors such as the network traffic at the time that you make the request, multiple requests from the same host may be directed to different servers by the authoritative DNS server. This is accomplished by returning different IP addresses to your machine.

FWIW, both ping and socket.gethostbyname() for google.com resolve to 216.58.217.14 on my machine, running OS X Yosemite.

komaromy
  • 221
  • 2
  • 12