Qt 如何获取本机ip地址

QString myClient::getMyIpString()
{ 
    QString ip_address;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses(); // 获取所有ip
    for (int i = 0; i < ipAddressesList.size(); ++i)
    { 
        
        QHostAddress ipAddr = ipAddressesList.at(i);
        if ((ipAddr.protocol() == QAbstractSocket::IPv4Protocol))// 筛选出ipv4
        { 
            qDebug() << "----ipv4: " << ipAddr.toString();
            if (!ipAddr.toString().startsWith("169"))// 过滤掉网卡,路由器等的ip
            { 
                ip_address = ipAddr.toString();
                break;
            }


        }
    }
    if (ip_address.isEmpty())
        ip_address = QHostAddress(QHostAddress::LocalHost).toString();
    return ip_address;
}
    原文作者:卧_听风雨
    原文地址: https://blog.csdn.net/birenxiaofeigg/article/details/124272022
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞