c++ - 如何获取 IP 地址(IPv4 为 NULL,但 IPv6 存在),内容详情

标签 c++ c linux networking

对不起,标题可能会混淆。 例如,eth1 替代 br100。 所以eth1的ipv4地址是NULL。

/etc/网络/接口(interface)

br100 Link encap:Ethernet HWaddr 00:0c:29:75:e2:0a
inet addr:192.168.11.249 Bcast:192.168.11.255 Mask:255.255.255.0 inet6 addr: fe80::20c:29ff:fe75:e20a/64 Scope:Link

eth1 Link encap:Ethernet HWaddr 00:0c:29:75:e2:0a
inet6 addr: fe80::20c:29ff:fe75:e20a/64 Scope:Link

获取eth1的ipv4时如何读取NULL值?

这是我的 getipv4 函数:

sIPv4 = new string[giIfaceCount];
struct ifaddrs *ifAddrStruct;
struct ifaddrs *ifa;
void *tmpAddrPtr;
if (getifaddrs(&ifAddrStruct) == -1)
{
    perror("getifaddrs");
    exit(1);
}
int iFlag4 = 0;
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)
{
    if (ifa->ifa_addr->sa_family == AF_INET)
    {
        tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
        char addressBuffer[1024];
        if (strcmp(inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, 1024),"NULL") == 0)
        {
            cout << "addressBuffer = NULL" << endl;
        }
        else
        {
            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, 1024);
            if (strcmp(ifa->ifa_name,"lo") == 0)
            {
                continue;
            }
            else
            {
                *(sIPv4+iFlag4) = addressBuffer;
                testIPv4.append(addressBuffer);
                testIPv4.append(" ");
                iFlag4 = iFlag4+1;
            }
        }
    }
}

最佳答案

感谢大家,我已经解决了我的问题。

简而言之,我已经将所有功能(关于getIPv4getMACgetIPv6...)组合到getHostinfo功能。 然后,它通过一个for循环(Interface Count)一个一个地获取主机信息。

最后,我非常感谢大家。 ^__^

关于c++ - 如何获取 IP 地址(IPv4 为 NULL,但 IPv6 存在),内容详情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10427284/

相关文章:

c++ - 编译器错误 : unmatched call to pow(. ..)

c - 如果多个 pthread 使用相同的函数会发生什么

c++ - 使用 C/C++ 在 iOS 中写入文件

Linux读取外置磁盘数据,无法挂载

c++ - 限制多线程应用程序的处理器数量

.net - fatal error C1083 : Cannot open include file: 'vld.h' : No such file or directory

c++ - 使用 vector .sort() 无效使用非静态成员函数

c - 如何在C中获取字符串的最后一部分

c++ - 同一端口但不同接口(interface)上的多个广播接收

c++ - 将参数传递到 C++ 共享库