以下是用c++写的QT代码,如果要直接在C++上运行,代码需要稍微改改:

   QString Network::Get_Gate_Way() {
        #ifdef Q_OS_WIN
        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 ) {
            return("404");
        }
        return(rx.cap( 2 ) );
        #endif

        FILE *fp;
        char buf[512];
        char cmd[128];
        char gateway[30];
        char *tmp;

        #ifdef Q_OS_LINUX
            strcpy( cmd, "ip route" );
        #endif

        #ifdef Q_OS_MAC
            strcpy( cmd, "route get default | grep gateway" );
        #endif

        fp = popen( cmd, "r" );
        if ( NULL == fp ) {
            perror( "popen error" );
            /* 未获取到信息 */
            return("400");
        }

        #ifdef Q_OS_LINUX
            while ( fgets( buf, sizeof(buf), fp ) != NULL ) {
            tmp = buf;
            while ( *tmp && isspace( *tmp ) )
                        ++tmp;
            if ( strncmp( tmp, "default", strlen( "default" ) ) == 0 )
                        break;
        }
        sscanf( buf, "%*s%*s%s", gateway );
        printf( "default gateway:%s/n", gateway );
        pclose( fp );
        #endif

        #ifdef Q_OS_MAC
        QString gateway = fgets( buf, sizeof(buf), fp );
        pclose( fp );
        gateway = gateway.simplified().replace( QRegExp( "gateway: " ), "" );
        #endif

        return(gateway);
    }
Last modification:July 27th, 2021 at 05:17 pm
如果觉得我的文章对你有用,请随意赞赏