栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ 使用gethostbyname

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++ 使用gethostbyname

前一帖子,实验了如何使用adns库实现解析,用起来还是麻烦,直接使用系统函数,更直接:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include   // dns

///static thread_local 
char t_resolveBuffer[64 * 1024];

void test(const char *url)
{

    char ip[INET_ADDRSTRLEN];
     char *ptr, **pptr;

    struct hostent hostinfo;
    struct hostent *phost = NULL;
    int hostrrno = 0;
    memset(&hostinfo, 0, sizeof(hostinfo));

    //该函数成功返回0,失败返回一个非0的数。
    int ret = gethostbyname_r(url, &hostinfo, t_resolveBuffer, sizeof(t_resolveBuffer), &phost, &hostrrno);

    if (ret == 0 && phost != NULL)
    {
        // assert(phost->h_addrtype == AF_INET && phost->h_length == sizeof(uint32_t));
        // out->addr_.sin_addr = *reinterpret_cast(phost->h_addr);
        printf("official hostname: %sn", phost->h_name);

        for (pptr = phost->h_aliases; *pptr != NULL; pptr++)
        {
            printf("talias: %sn", *pptr);
        }
        switch (phost->h_addrtype)
        {
        case AF_INET:
            pptr = phost->h_addr_list;
            for (; *pptr != NULL; pptr++)
            {
                // inet_ntoa只适用于ipv4地址,而inet_ntop适用ipv4和ipv6地址
                printf("taddress: %sn", inet_ntop(phost->h_addrtype, *pptr, ip, sizeof(ip)));
            }
            break;
        default:
            printf("unknow address type.");
            break;
        }
    }
    else
    {
        printf("ret =%d, err=%dn", ret, hostrrno);
        return;
    }
}

int main()
{

    char host[128];

    res_init();

    while (1)
    {

        scanf("%s", host);
        if (strlen(host) == 4 && 0 == strcmp(host, "exit"))
            break;
        test(host);
    }

    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/879407.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号