当前位置: 萬仟网 > IT编程>开发语言>C/C++ > linux网络编程——域名转换 gethostbyname与gethostbyaddr

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

2018年11月21日  | 萬仟网IT编程  | 我要评论
域名转换 还有一个类似的函数 gethostbyaddr,通过ip地址获取到规范名,别名等信息 ...

域名转换

#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;
}

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


#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;
}


版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

相关文章:

验证码:
Copyright © 2017-2021  萬仟网 保留所有权利. 粤ICP备17035492号-1
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com