1. 程式人生 > >linux系統C語言實現域名解析功能

linux系統C語言實現域名解析功能

版權宣告:本文為遲思堂主人李遲原創文章,版權所有。可隨便任意使用(包括學習研究商用),但由此帶來的成果或後果,概與作者無關。胡亂修改的,不註明出處的,概不負責。 https://blog.csdn.net/subfate/article/details/81776147
背景

後臺專案劃分幾個小服務,分別部署到不同的docker容器中,不同服務通過socket連線,docker的IP地址是由dockerd自動分配的,當然,也可以固定IP,但這樣不好。因此,為了方便部署和維護,考慮通過容器別名的方式。容器名通過ini配置檔案傳遞到程式裡,程式需要根據容器名解析出對應的IP地址。於是找了些實現域名解析的方法。
網上有用boost庫實現的,但這個庫太龐大了,不適用,後來發現linux下有gethostbyname函式可以實現。於是參考網上資料寫了一個介面。
實現介面

// 注:如需獲取網站IP地址,引數填寫域名即可,不需加"http://"
int socket_resolver(const char *domain, char* ipaddr)
{
    if (!domain || !ipaddr) return -1;

    struct hostent* host=gethostbyname(domain);
    if (!host)
    {
        return -1;
    }

    // 獲取第一個IP地址
    strncpy(ipaddr, inet_ntoa(*(in_addr*)host->h_addr), 16);

    #if 0
    // 獲取所有的地址
    for (int i = 0; host->h_addr_list[i]; i++)
    {
        //printf("%d ip: %s\n", i, inet_ntoa(*(in_addr*)host->h_addr_list[i]));
    }
    #endif

    return 0;
}

測試函式

測試程式如下:

#include <string>
#include <iostream>
void main()
{
    //char* hostname = "www.latelee.com";//"www.baidu.com";//"latelee-wordpress";
    char* hostname = "172.18.18.168";
    char ip[16] = {0};

    socket_resolver("www.latelee.com", ip);
    printf("dddd: %s\n", ip);
    socket_resolver("www.baidu.com", ip);
    printf("dddd: %s\n", ip);
    socket_resolver("latelee-wordpress", ip);
    printf("dddd: %s\n", ip);

    socket_resolver("172.18.18.18", ip);
    printf("dddd: %s\n", ip);

    std::string domain;
    std::string ipstr;
    ipstr.resize(16);
    domain = "www.baidu.com";
    socket_resolver(domain.data(), (char*)ipstr.c_str());
    printf("dddd: %s\n", ipstr.c_str());
}

小結

對於容器之間的網路連線,建議使用容器別名的方式,因為容器別名可以在docker run或docker-compose.yml中指定,從而不會因為容器IP變化而修改程式碼或配置檔案。

李遲 2018.8.17 中午休息前
---------------------  
作者:李遲  
來源:CSDN  
原文:https://blog.csdn.net/subfate/article/details/81776147  
版權宣告:本文為博主原創文章,轉載請附上博文連結!