I am trying to create a simple program that gets the IP address given a certain hostname:
My code snipped is attached below:
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <errno.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if(argc < 2){
printf("Please provide a hostname.\n");
exit(1);
}
char *hostname = argv[1];
char ip[100];
get_ip(hostname, ip);
printf("%s resolved to %s\n", hostname,ip);
}
int get_ip(char *hostname, char *ip){
struct sockaddr_in *h;
int sockfd;
struct addrinfo hints, *servinfo,*res;
struct addrinfo *iter;
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if((rv = getaddrinfo(hostname, "HTTP", &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo %s\n", gai_strerror(rv));
return 1;
}
for(iter=res; iter != NULL; iter=iter->ai_next){
printf("%p\n", iter->ai_next);
h=(struct sockaddr_in *)iter->ai_addr;
strcpy(IP, inet_ntoa(h->sin_addr));
printf("%s\n",ip);
}
freeaddrinfo(res);
return 0;
}
I enter in the following arguments:
gcc get_ip_addr.c -o get_ip_addr;
./get_ip_addr google-public-dns-b.google.com
This results in:
0x2475330
8.8.4.4
(nil)
0.0.0.0
When I remove the "http"
and &hints
and set them to NULL
I get the following results:
0x1b63310
8.8.4.4
0x1b63360
8.8.4.4
0x1b633b0
8.8.4.4
0x1b63410
0.0.0.0
0x1b63470
0.0.0.0
(nil)
0.0.0.0
So when I set the service
and hints
to NULL
the getaddrinfo()
returns multiple possible results I don't understand why I am getting multiple IP addresses instead of just getting one IP address?