您的位置:首页 > 编程语言 > Qt开发

QT 获取本地IP MAC地址

2016-11-22 15:23 399 查看
std::string CControl::gethostIp()

{

    QString strIpAddress;

    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();

    // 获取第一个本主机的IPv4地址

    int nListSize = ipAddressesList.size();

    for (int i = 0; i < nListSize; ++i)

    {

       if (ipAddressesList.at(i) != QHostAddress::LocalHost &&

           ipAddressesList.at(i).toIPv4Address())

       {

           strIpAddress = ipAddressesList.at(i).toString();

           break;

       }

     }

     // 如果没有找到,则以本地IP地址为IP

     if (strIpAddress.isEmpty())

        strIpAddress = QHostAddress(QHostAddress::LocalHost).toString();

     return strIpAddress.toStdString();

}

std::string CControl::gethostMac()

{

    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表

    int nCnt = nets.count();

    QString strMacAddr = "";

    for(int i = 0; i < nCnt; i ++)

    {

        // 如果此网络接口被激活并且正在运行并且不是回环地址,则就是我们需要找的Mac地址

        if(nets[i].flags().testFlag(QNetworkInterface::IsUp) && nets[i].flags().testFlag(QNetworkInterface::IsRunning)

                && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))

        {

            strMacAddr = nets[i].hardwareAddress();

            break;

        }

    }

    return strMacAddr.toStdString();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: