ubuntu(Linux) c++ 获取本机IPv4和ipv6、查询本机IPv4,IPv6

1.关于

演示环境:

Linux xxxxxxx 5.4.0-47-generic #51-Ubuntu SMP Fri Sep 4 19:50:52 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

代码来自 StackOverflow But,自己做了部分修改。

2.头文件

#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

3.ipv4获取

调用函数get_ip_linux可以获取本机ipv4

int net_adapter_helper::get_ipv4_linux(std::list<std::string>& out_list_ip4)
{
    return get_ip_linux(AF_INET, out_list_ip4); 
}

4.ipv6获取

调用函数get_ip_linux可以获取本机ipv6

int net_adapter_helper::get_ipv6_linux(std::list<std::string>& out_list_ip6)
{
    return get_ip_linux(AF_INET6, out_list_ip6); 
}

5.get_ip_linux封装

这里封装,目的是为了更方便维护获取本机IP的代码。通过第一个参数控制当前需要获取ipv4还是ipv6

int net_adapter_helper::get_ip_linux(int ipv4_6, std::list<std::string>& out_list_ip)
{
    int ret_val = 0;

    struct ifaddrs * ifAddrStruct 	= NULL;
    void * tmpAddrPtr 				= NULL;

    // 1.
    ret_val 						= getifaddrs(&ifAddrStruct);
    if (0 != ret_val)
    {
        ret_val = errno;

        return ret_val;
    }

    // 2.
    std::string str_ipvX;

    int padress_buf_len = 0;
    char addressBuffer[INET6_ADDRSTRLEN] = {0};

    if (AF_INET6 == ipv4_6)
            padress_buf_len = INET6_ADDRSTRLEN;
    else
        padress_buf_len = INET_ADDRSTRLEN;
    
    
    while (NULL != ifAddrStruct ) 
    {
        if (ipv4_6 == ifAddrStruct->ifa_addr->sa_family ) 
        { 
            // is a valid IP4 Address
            tmpAddrPtr = &((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
            
            inet_ntop(ipv4_6, tmpAddrPtr, addressBuffer, padress_buf_len);
            str_ipvX = std::string(addressBuffer);

            out_list_ip.push_back(str_ipvX);

            memset(addressBuffer, 0, padress_buf_len);
        } 

        ifAddrStruct=ifAddrStruct->ifa_next;
    }

    return ret_val;
}

6.测试结果

  • 6.1 调用代码
std::list<std::string> ipv4;
std::list<std::string> ipv6;

int ret_val = net_adapter_helper::get().get_ipv4_linux(ipv4);
if (0 != ret_val)
{
    cout << "error, ipv4, id = " << ret_val << endl;
}
else
{
    int index = 0;
    for (auto item: ipv4)
    {
        cout << "index = " << ++index;
        cout << ", ipv4 = " << item.c_str() << endl;
    }
}


ret_val = net_adapter_helper::get().get_ipv6_linux(ipv6);
if (0 != ret_val)
{
    cout << "error, ipv6, id = " << ret_val << endl;
}
else
{
    int index = 0;
    for (auto item: ipv6)
    {
        cout << "index = " << ++index;
        cout << ", ipv6 = " << item.c_str() << endl;
    }
}
  • 6.2 输出结果:
posted @ 2020-10-01 11:35  mohist  阅读(2861)  评论(0编辑  收藏  举报