4

I am trying to resolve a URL's IP address using getaddrinfo(), but it always returns the wrong IP address, I have tried with several URL's and the result is same. any help wold be greatly appreciated.

The program returnes the ip address : 209.85.175.99 insted of returning the real IP which is 74.125.39.147

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int
main()
{
 char *hostname = "www.google.lk";
 struct addrinfo hints, *res;
 struct in_addr addr;
 int err;

 memset(&hints, 0, sizeof(hints));
 hints.ai_socktype = SOCK_STREAM;
 hints.ai_family = AF_INET;

 if ((err = getaddrinfo(hostname, NULL, &hints, &res)) != 0) {
 printf("error %d\n", err);
 return 1;
 }

 addr.s_addr = ((struct sockaddr_in *)(res->ai_addr))->sin_addr.s_addr;

 printf("ip address : %s\n", inet_ntoa(addr));

 freeaddrinfo(res);

 return 0;
}
glglgl
  • 89,107
  • 13
  • 149
  • 217
Ashwin
  • 57
  • 1
  • 1
  • 2
  • are you behind some kind of proxy? or is there something wrong in your etc/hosts ? – phoet Oct 11 '11 at 11:49
  • Are you sure you are getting a wrong one? >nslookup www.google.lk Server: dir-320 Address: 192.168.0.1 Non-authoritative answer: Name: www.l.google.com Addresses: 209.85.148.147 209.85.148.99 209.85.148.103 209.85.148.104 209.85.148.105 209.85.148.106 Aliases: www.google.lk www.google.com – Roman R. Oct 11 '11 at 11:49
  • 3
    Maybe you should try with a name that has a more straightofrward resolution than a Google server with multiple layers of aliasing and round-robin resolution. How about `stackoverflow.com`? (The resolution of Google server names even depends on the location from where you resolve them.) – Sven Marnach Oct 11 '11 at 11:50
  • Thanks for all your help, I solved the problem, there was nothing wrong in the coding, the URL I was using was the problem, as Seven suggested stackoverflow.com is resolved correctly. Thanks again. – Ashwin Oct 11 '11 at 12:42
  • 1
    Though i might add..... getaddrinfo() returns a **list** of addresses. Check out the man page for an example on how to iterate over the results. – Brian McFarland Oct 11 '11 at 14:17
  • use `-Wall`, some of the header files are missing.. – Karoly Horvath Nov 13 '11 at 20:51

1 Answers1

6

google.com can resolve to different IP addresses depending on your own location. It's kind of load balancing trick.

blaze
  • 4,326
  • 18
  • 23