Qt获取本机正在使用的IP和Mac地址(过滤未使用的 过滤虚拟机的 过滤链路的)

 获取本地Mac地址( 排除虚拟机Mac地址 )

VM 虚拟机地址的Mac固定为 00:50:56:C0:00:01 和 00:50:56:C0:00:08

QString Window::getHostMacAddress()
{
    qDebug() << "getHostMacAddress";
    QList nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();

    QString strMacAddr = "";
    for(int i = 0; i < nCnt; i ++)
    {
        //00:50:56:C0:00:01 00:50:56:C0:00:08虚拟机地址
        // 如果此网络接口被激活并且正在运行并且不是回环地址,则就是我们需要找的Mac地址
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp) && nets[i].flags().testFlag(QNetworkInterface::IsRunning)
                && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack) &&  nets[i].hardwareAddress() != "00:50:56:C0:00:01" && nets[i].hardwareAddress() != "00:50:56:C0:00:08" )
        {
            strMacAddr = nets[i].hardwareAddress();
            break;
        }
    }
    return strMacAddr;
}

获取本地IP地址( 排除虚拟机IP地址和链路IP地址 )

  QString  Window::getHostAddress()  
{
	QString hostAddr = "";
    QList nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();

    //排除虚拟机地址
    for(int i = 0; i < nCnt; i ++) {
        if (  nets[i].hardwareAddress() == "00:50:56:C0:00:01" ) {
            nets.removeAt( i );
            break;
        }
    }
    nCnt = nets.count();
    for(int i = 0; i < nCnt; i ++) {
        if (  nets[i].hardwareAddress() == "00:50:56:C0:00:08" ) {
            nets.removeAt( i );
            break;
        }
    }

    foreach(QNetworkInterface interface,nets) {
        //排除不在活动的IP
        if( interface.flags().testFlag(QNetworkInterface::IsUp) && interface.flags().testFlag(QNetworkInterface::IsRunning ) ){
            QList entryList = interface.addressEntries();
            foreach(QNetworkAddressEntry entry,entryList) {
                QHostAddress hostAddress = entry.ip();

                if ( hostAddr.isEmpty() ) {
                    //排除本地地址
                    if ( hostAddress != QHostAddress::LocalHost && hostAddress.toIPv4Address() ) {
                        quint32 nIPV4 = hostAddress.toIPv4Address();

                        //本地链路地址
                        quint32 nMinRange = QHostAddress("169.254.1.0").toIPv4Address();
                        quint32 nMaxRange = QHostAddress("169.254.254.255").toIPv4Address();
                        //排除链路地址
                        if ( ( nIPV4 >= nMinRange ) && ( nIPV4 <= nMaxRange ) )
                            continue;
                        qDebug() << hostAddress;
                        hostAddr = hostAddress.toString();
						return hostAddr;
                    }
                }

            }
        }
    }
	return QHostAddress::Null;
}

 

 

 

 

 

你可能感兴趣的:(Qt)