Qt獲取本機ip地址


情景:

最近有個項目需要手機可以與PC進行tcp傳輸文件,PC做server時在我的電腦可以,在其他電腦時手機連接超時。
查看了端口,防火牆等等問題未能解決。最后發現是qt在獲取IP地址時獲取錯了,獲取的是第一個而不是正在使用的。

下面是Qt獲取本機正在使用的IP地址:

QString strIpAddress;
QProcess cmd_pro ;
QString cmd_str = QString("ipconfig");
cmd_pro.start("cmd.exe", QStringList() << "/c" << cmd_str);
cmd_pro.waitForStarted();
cmd_pro.waitForFinished();
QString result = cmd_pro.readAll();
qDebug() << result;
QString pattern("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
QRegExp rx(pattern);

int pos = 0;
bool found = false;
while((pos = rx.indexIn(result, pos)) != -1){
    QString tmp = rx.cap(0);
    //跳過子網掩碼 eg:255.255.255.0
    if(-1 == tmp.indexOf("255")){
       if(strIpAddress != "" && -1 != tmp.indexOf(strIpAddress.mid(0,strIpAddress.lastIndexOf(".")))){
            found = true;
            break;
        }
        strIpAddress = tmp;
    }
    pos += rx.matchedLength();
}

qDebug()<<"ip: " << strIpAddress;

參考鏈接:https://blog.csdn.net/JakeLinfly/article/details/96590688


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM