Here are 2 methods to get the ip address of a hostname :
The first method uses the traditional gethostbyname function to retrieve information about a hostname/domain name.
Code
1 |
#include<stdio.h> //printf |
2 |
#include<string.h> //memset |
3 |
#include<stdlib.h> //for exit(0); |
5 |
#include<errno.h> //For errno - the error number |
6 |
#include<netdb.h> //hostent |
9 |
int hostname_to_ip( char * , char *); |
11 |
int main( int argc , char *argv[]) |
15 |
printf ( "Please provide a hostname to resolve" ); |
19 |
char *hostname = argv[1]; |
22 |
hostname_to_ip(hostname , ip); |
23 |
printf ( "%s resolved to %s" , hostname , ip); |
32 |
int hostname_to_ip( char * hostname , char * ip) |
35 |
struct in_addr **addr_list; |
38 |
if ( (he = gethostbyname( hostname ) ) == NULL) |
41 |
herror( "gethostbyname" ); |
45 |
addr_list = ( struct in_addr **) he->h_addr_list; |
47 |
for (i = 0; addr_list[i] != NULL; i++) |
50 |
strcpy (ip , inet_ntoa(*addr_list[i]) ); |
Compile and Run
1 |
$ gcc hostname_to_ip.c && ./a.out www.google.com |
2 |
www.google.com resolved to 74.125.235.16 |
4 |
$ gcc hostname_to_ip.c && ./a.out www.msn.com |
5 |
www.msn.com resolved to 207.46.140.34 |
7 |
$ gcc hostname_to_ip.c && ./a.out www.yahoo.com |
8 |
www.yahoo.com resolved to 98.137.149.56 |
The second method uses the getaddrinfo function to retrieve information about a hostname/domain name.
Code
1 |
#include<stdio.h> //printf |
2 |
#include<string.h> //memset |
3 |
#include<stdlib.h> //for exit(0); |
5 |
#include<errno.h> //For errno - the error number |
6 |
#include<netdb.h> //hostent |
9 |
int hostname_to_ip( char * , char *); |
11 |
int main( int argc , char *argv[]) |
15 |
printf ( "Please provide a hostname to resolve" ); |
19 |
char *hostname = argv[1]; |
22 |
hostname_to_ip(hostname , ip); |
23 |
printf ( "%s resolved to %s" , hostname , ip); |
32 |
int hostname_to_ip( char *hostname , char *ip) |
35 |
struct addrinfo hints, *servinfo, *p; |
36 |
struct sockaddr_in *h; |
39 |
memset (&hints, 0, sizeof hints); |
40 |
hints.ai_family = AF_UNSPEC; |
41 |
hints.ai_socktype = SOCK_STREAM; |
43 |
if ( (rv = getaddrinfo( hostname , "http" , &hints , &servinfo)) != 0) |
45 |
fprintf (stderr, "getaddrinfo: %s\n" , gai_strerror(rv)); |
50 |
for (p = servinfo; p != NULL; p = p->ai_next) |
52 |
h = ( struct sockaddr_in *) p->ai_addr; |
53 |
strcpy (ip , inet_ntoa( h->sin_addr ) ); |
56 |
freeaddrinfo(servinfo); |
Compile and Run
1 |
$ gcc hostname_to_ip.c && ./a.out www.google.com |
2 |
www.google.com resolved to 74.125.235.19 |
4 |
$ gcc hostname_to_ip.c && ./a.out www.yahoo.com |
5 |
www.yahoo.com resolved to 72.30.2.43 |
7 |
$ gcc hostname_to_ip.c && ./a.out www.msn.com |
8 |
www.msn.com resolved to 207.46.140.34 |