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

域名转换

#include <netdb.h>
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 <stdio.h>
#include <netdb.h>
#include <arpa/inet.h>

int main(void)
{
    struct hostent* hent;
    int i = 0;
    char addr[16];
    // 通过域名获取IP信息
    hent = gethostbyname("www.baidu.com");
    printf("h_name: %s\n", hent->h_name);

    while (hent->h_aliases[i] != NULL)
        printf("aliase: %s\n", hent->h_aliases[i++]);

    i = 0;
    while (hent->h_addr_list[i] != NULL)
        printf("ip addr %s\n", inet_ntop(hent->h_addrtype,hent->h_addr_list[i++], addr, sizeof(addr)));

    return 0;
}

1539935-20181120151332207-1246748516.png

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

gethostbyaddr.png
1539935-20181120151441392-1145023159.png

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
 
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:%s\n", strerror(errno));
        return -1;
    }
 
    phost = gethostbyaddr((const char*)&addr, sizeof(addr), AF_INET);
    if (phost == NULL) {
        printf("gethostbyaddr error:%s\n", strerror(h_errno));
        return -1;
    }   
 
    printf("host name:%s\n", phost->h_name);
 
    return 0;
}

gethostbyaddr2.png
1539935-20181120151459657-292091295.png

转载于:https://www.cnblogs.com/zmf96/p/9988658.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值