static void getGateway( QString &gateway)
{
    QProcess cmd_pro ;
    QString cmd_str = QString("route print");
    cmd_pro.start("cmd.exe", QStringList() << "/c" << cmd_str);
    cmd_pro.waitForStarted();
    cmd_pro.waitForFinished();
    QString result = cmd_pro.readAll();
    QString pattern("0\.0\.0\.0 *(0|128)\.0\.0\.0 *([0-9\.]*)");
    QRegExp rx(pattern);
    int pos = result.indexOf(rx);
    if (pos >= 0)
    {
        qDebug()<<"reg::"<<rx.cap(2);
        gateway = rx.cap(2);
    }
}

另一种用windowsAPI实现,但是windows10 下用无线连接获取失败
static void getGateway(QString &netmask, QString &gateway)
{
    PIP_ADAPTER_INFO pIpAdapterInfo = new IP_ADAPTER_INFO();
    unsigned long stSize = sizeof(IP_ADAPTER_INFO);
    int nRel = GetAdaptersInfo(pIpAdapterInfo,&stSize);
    if (ERROR_BUFFER_OVERFLOW == nRel){
        delete pIpAdapterInfo;
        pIpAdapterInfo = (PIP_ADAPTER_INFO)new BYTE[stSize];
        nRel=GetAdaptersInfo(pIpAdapterInfo,&stSize);
    }
    if (ERROR_SUCCESS == nRel){
        while (pIpAdapterInfo){
            switch(pIpAdapterInfo->Type){
            case MIB_IF_TYPE_OTHER:
                break;
            case MIB_IF_TYPE_ETHERNET:
                break;
            case MIB_IF_TYPE_TOKENRING:
                break;
            case MIB_IF_TYPE_FDDI:
                break;
            case MIB_IF_TYPE_PPP:
                break;
            case MIB_IF_TYPE_LOOPBACK:
                break;
            case MIB_IF_TYPE_SLIP:
                break;
            default:
                break;
            }
            for (DWORD i = 0; i < pIpAdapterInfo->AddressLength; i++)
                if (i < pIpAdapterInfo->AddressLength-1){
                }
                else{
                }
            IP_ADDR_STRING *pIpAddrString =&(pIpAdapterInfo->IpAddressList);
            do{
                if(QString(pIpAddrString->IpAddress.String) == getHostIpByWinSock()){
                    gateway = QString(pIpAdapterInfo->GatewayList.IpAddress.String);
                    //netmask = QString(pIpAdapterInfo->IpAddressList.IpMask.String);
                    return;
                }
                pIpAddrString=pIpAddrString->Next;
            } while (pIpAddrString);
            pIpAdapterInfo = pIpAdapterInfo->Next;
        }
    }
    if (pIpAdapterInfo){
        delete pIpAdapterInfo;
    }
    gateway = QString("0.0.0.0");
}

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐