多个默认网关正在获取

Multiple default gateways getting

本文关键字:获取 网关 默认      更新时间:2023-10-16

我在C++中有一个程序,它正在获得默认网关,所以它可以正常工作,直到我在几乎没有默认网关的PC上尝试它这是我的代码:

DWORD Err,AdapterInfoSize =0;
    PIP_ADAPTER_INFO pAdapterInfo, pAdapt;
    if ((Err = GetAdaptersInfo(NULL, &AdapterInfoSize)) != 0) {
        if (Err != ERROR_BUFFER_OVERFLOW){
            std::cout<<"ERROR S05n";
            cin.ignore();
        }
    }
    if ((pAdapterInfo = (PIP_ADAPTER_INFO) GlobalAlloc(GPTR, AdapterInfoSize)) == NULL) {
        std::cout<<"ERROR S06n";
        cin.ignore();
    }
    if ((Err = GetAdaptersInfo(pAdapterInfo, &AdapterInfoSize)) != 0) {
        std::cout<<"ERROR S07n";
        cin.ignore();
    }
    pAdapt = pAdapterInfo;
    while (pAdapt){
        dfltgw = pAdapt->GatewayList.IpAddress.String;
        break;
    }
    pAdapt = pAdapterInfo;
    cout << endl << "DEFAULT GATEWAY: " << dfltgw << endl;

PC上,我有一个VirtualBox的虚拟网络,我总是得到输出:0.0.0.0,在我有1个默认网关的PC上,我得到正确的IP。

那么我该怎么解决呢?

通过添加修复了它

for (int izjson = 0; izjson < 50; izjson++) {
        string checkdf = pAdapterInfo->GatewayList.IpAddress.String;
        if(checkdf != "0.0.0.0") {
            dfltgw = checkdf;
            break;
        }
        pAdapterInfo = pAdapterInfo->Next; // Get next adapter info
    }

感谢@SergeyA

您得到了系统中安装的所有适配器的列表,但您只检查了第一个适配器(您的整个while循环是无意义的,您在第一次迭代后就将其中断)。相反,您应该迭代您的适配器,直到找到合适的适配器。

为了回答评论中的一些困惑,假设默认网关是全局(而不是每个适配器)设置,下面是ipconfig输出的复制粘贴:Windows IP配置

Ethernet adapter Local Area Connection 11:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::4149:4c25:692d:dfec%91
   IPv4 Address. . . . . . . . . . . : 10.252.26.84
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :
Wireless LAN adapter Wireless Network Connection 14:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::79a2:afc8:7cd0:79ac%72
   IPv4 Address. . . . . . . . . . . : 192.168.10.9
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.10.1