linux gethostbyname 源码,linux网络编程——域名转换 gethostbyname与gethostbyaddr

域名转换

#include

struct hostent *gethostbyname(const char *name);

参数: name: 执行主机名的指针

返回值: 返回一个hostent指针

struct hostent

{

char *h_name; // 表示主机的规范名

char **h_aliases; // 表示主机的别名,别名可能有多个

int h_addrtype; // 表示的是主机ip地址的类型, ipv4 AF_iNET 或 ipv6 AFINET6

int h_length; // 表示主机ip地址的长度

char ** h_addr_list; // 表示的是主机的ip地址

}

#include

#include

#include

int main(void)

{

struct hostent* hent;

int i = 0;

char addr[16];

// 通过域名获取IP信息

hent = gethostbyname("www.baidu.com");

printf("h_name: %sn", hent->h_name);

while (hent->h_aliases[i] != NULL)

printf("aliase: %sn", hent->h_aliases[i++]);

i = 0;

while (hent->h_addr_list[i] != NULL)

printf("ip addr %sn", inet_ntop(hent->h_addrtype,hent->h_addr_list[i++], addr, sizeof(addr)));

return 0;

}

a446ee54a11219061ab5689215cb158e.png

还有一个类似的函数 gethostbyaddr,通过ip地址获取到规范名,别名等信息

gethostbyaddr.png

460f0b679c683fbe57e7bc63584d6755.png

#include

#include

#include

#include

#include

#include

#include

#include

int main(int argc, char **argv)

{

struct in_addr addr;

struct hostent *phost;

if (inet_pton(AF_INET, argv[1], &addr) <= 0) {

printf("inet_pton error:%sn", strerror(errno));

return -1;

}

phost = gethostbyaddr((const char*)&addr, sizeof(addr), AF_INET);

if (phost == NULL) {

printf("gethostbyaddr error:%sn", strerror(h_errno));

return -1;

}

printf("host name:%sn", phost->h_name);

return 0;

}

gethostbyaddr2.png

3b1c2a9e0effe30e656a28324fbe8165.png

内容来源于网络如有侵权请私信删除

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值