有时候需要用到ip地址,但是有时候有虚拟机,需要剔除。
转自:https://blog.csdn.net/qq_38008379/article/details/103683946
获取本地IP地址( 排除虚拟机IP地址和链路IP地址 ):
1 QString Window::getHostAddress() 2 { 3 QString hostAddr = ""; 4 QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表 5 int nCnt = nets.count(); 6 7 //排除虚拟机地址 8 for(int i = 0; i < nCnt; i ++) { 9 if ( nets[i].hardwareAddress() == "00:50:56:C0:00:01" ) { 10 nets.removeAt( i ); 11 break; 12 } 13 } 14 nCnt = nets.count(); 15 for(int i = 0; i < nCnt; i ++) { 16 if ( nets[i].hardwareAddress() == "00:50:56:C0:00:08" ) { 17 nets.removeAt( i ); 18 break; 19 } 20 } 21 22 foreach(QNetworkInterface interface,nets) { 23 //排除不在活动的IP 24 if( interface.flags().testFlag(QNetworkInterface::IsUp) && interface.flags().testFlag(QNetworkInterface::IsRunning ) ){ 25 QList<QNetworkAddressEntry> entryList = interface.addressEntries(); 26 foreach(QNetworkAddressEntry entry,entryList) { 27 QHostAddress hostAddress = entry.ip(); 28 29 if ( hostAddr.isEmpty() ) { 30 //排除本地地址 31 if ( hostAddress != QHostAddress::LocalHost && hostAddress.toIPv4Address() ) { 32 quint32 nIPV4 = hostAddress.toIPv4Address(); 33 34 //本地链路地址 35 quint32 nMinRange = QHostAddress("169.254.1.0").toIPv4Address(); 36 quint32 nMaxRange = QHostAddress("169.254.254.255").toIPv4Address(); 37 //排除链路地址 38 if ( ( nIPV4 >= nMinRange ) && ( nIPV4 <= nMaxRange ) ) 39 continue; 40 qDebug() << hostAddress; 41 hostAddr = hostAddress.toString(); 42 return hostAddr; 43 } 44 } 45 46 } 47 } 48 } 49 return QHostAddress::Null; 50 }
获取本地Mac地址( 排除虚拟机Mac地址 )
VM 虚拟机地址的Mac固定为 00:50:56:C0:00:01 和 00:50:56:C0:00:08:
QString Window::getHostMacAddress() { qDebug() << "getHostMacAddress"; QList<QNetworkInterface> 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; }
标签:00,ip,56,50,地址,C0,本机,nets From: https://www.cnblogs.com/warmlight/p/16612859.html