Linux-C 根据域名获取IP地址
一、简述
记--根据域名获取对应的IP地址。
二、效果
三、代码
/* File:main.c
* Desciption:Get ip address from domain name.
* Author:Genven_Liang
* Date:2020-05-02
* Version:V1.0.0.1
*/
#include #include #include #include #include //一个IP地址的最大长度限制
#define IP_LEN64
/* 函数名:printDomainNameInfo
* 作用:打印域名相关信息
* 参数:
* domain_name:域名
* 返回值:
* -1:失败
* ==0:成功
*/
int printDomainNameInfo(char* domain_name)
{
struct hostent* host = NULL;
host = gethostbyname(domain_name);
if(NULL == host)
{
return -1;
}
printf("domain name:%s\n", domain_name);
printf("h_name:%s\n", host->h_name);
int i;
for(i=0; host->h_aliases[i] != NULL; i++)
{
printf("h_aliases%d:%s\n", i+1, host->h_aliases[i]);
}
printf("h_addrtype:%d (%s)\n", host->h_addrtype, (host->h_addrtype == AF_INET) ? "AF_INET" : "AF_INET6");
printf("h_length:%d\n", host->h_length);
char tmpStr[128] = {0};
for(i=0; host->h_addr_list[i] != NULL; i++)
{
memset(tmpStr, 0, sizeof(tmpStr));
inet_ntop(host->h_addrtype, host->h_addr_list[i], tmpStr, IP_LEN);
printf("Ip%d:%s\n", i+1, tmpStr);
}
return 0;
}
/* 函数名:getIpFormDomainName
* 作用:根据域名获取IP
* 参数:
* domain_name:域名
* ip:获取到的IP
* 返回值:
* -1:失败
* ==0:成功
*/
int getIpFormDomainName(char* domain_name, char* ip, unsigned char ipLen)
{
struct hostent* host = NULL;
host = gethostbyname(domain_name);
if(NULL == host)
{
return -1;
}
inet_ntop(host->h_addrtype, host->h_addr, ip, ipLen);
return 0;
}
/* 函数名:getAllIpFormDomainName
* 作用:根据域名获取所有IP
* 参数:
* domain_name:域名
* ipList:获取到的所有IP,以空格分割
* len:ipList的可用长度
* 返回值:
* -1:失败
* >=0:获取到的IP个数
*/
int getAllIpFormDomainName(char* domain_name, char* ipList, unsigned char _ipListLen, unsigned char ipLen)
{
struct hostent* host = NULL;
host = gethostbyname(domain_name);
if(NULL == host)
{
return -1;
}
int i;
int len = 0;
int ipCnt = 0;//IP的个数
int pos = 0;
char tmpIp[IP_LEN];
for(i=0; host->h_addr_list[i] != NULL; i++)
{
memset(tmpIp, 0, sizeof(tmpIp));
inet_ntop(host->h_addrtype, host->h_addr_list[i], tmpIp, ipLen);
len = strlen(tmpIp);
if(len>0 && pos0)
{
printf("All ip:%s\n", ip);
}
else
{
printf("get all ip from domain failed.\n");
}
return 0;
}
四、总结
4.1 hostent结构体定义在
hostent结构体定义在struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* 别名,可多个 */
int h_addrtype; /* 地址类型,IPv4、IPv6 */
int h_length; /* length of address */
char **h_addr_list; /* IP地址列表,可能有多个IP */
}
#define h_addr h_addr_list[0] /* 第一个IP地址 */
更多信息请查看手册:man gethostbyname