Академический Документы
Профессиональный Документы
Культура Документы
com/hostname-to-ip-address-c-sockets-linux/
Google+
Socket applications often need to convert hostnames like google.com to their corresponding ip address. This is done through dns
requests. The socket api in linux provides functions like gethostbyname and getaddrinfo that can be used to perform the dns requests
and get the ip address.
gethostbyname
The first method uses the traditional gethostbyname function to retrieve information about a hostname/domain name.
Code
#include<stdio.h> //printf
#include<string.h> //memset
#include<stdlib.h> //for exit(0);
#include<sys/socket.h>
#include<errno.h> //For errno - the error number
#include<netdb.h> //hostent
#include<arpa/inet.h>
1 of 5 05/03/19, 1:02 am
Get ip address from hostname in C using Linux sockets https://www.binarytides.com/hostname-to-ip-address-c-sockets-linux/
hostname_to_ip(hostname , ip);
printf("%s resolved to %s" , hostname , ip);
printf("\n");
}
/*
Get ip from domain name
*/
return 1;
}
2 of 5 05/03/19, 1:02 am
Get ip address from hostname in C using Linux sockets https://www.binarytides.com/hostname-to-ip-address-c-sockets-linux/
getaddrinfo
The second method uses the getaddrinfo function to retrieve information about a hostname/domain name. The getaddrinfo supports
ipv6 better.
Code
#include<stdio.h> //printf
#include<string.h> //memset
#include<stdlib.h> //for exit(0);
#include<sys/socket.h>
#include<errno.h> //For errno - the error number
#include<netdb.h> //hostent
#include<arpa/inet.h>
3 of 5 05/03/19, 1:02 am
Get ip address from hostname in C using Linux sockets https://www.binarytides.com/hostname-to-ip-address-c-sockets-linux/
char ip[100];
hostname_to_ip(hostname , ip);
printf("%s resolved to %s" , hostname , ip);
printf("\n");
}
/*
Get ip from domain name
*/
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next)
{
h = (struct sockaddr_in *) p->ai_addr;
strcpy(ip , inet_ntoa( h->sin_addr ) );
}
4 of 5 05/03/19, 1:02 am
Get ip address from hostname in C using Linux sockets https://www.binarytides.com/hostname-to-ip-address-c-sockets-linux/
5 of 5 05/03/19, 1:02 am