linux c 根据域名获取ip,Linux-C 根据域名获取IP地址

Linux-C 根据域名获取IP地址

一、简述

记--根据域名获取对应的IP地址。

二、效果

75a561e7ab272618f674e2d941f93268.png644db1887da7c1d5514f99108f7964b7.png

三、代码

/* 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

c33596b573881c0b98af2c80dd4d430b.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值