获取所有活动网卡
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
int ipInc = 0; QStringList ipList; ipList.clear(); QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses(); QList<QNetworkInterface> ipDevList = QNetworkInterface::allInterfaces(); #ifdef Q_OS_ANDROID ipList << "Android Boardcast"; #endif for (int i = 0; i < ipDevList.size(); ++i) { bool ipReady = false; QList<QNetworkAddressEntry> tmpIPlist = ipDevList.at(i).addressEntries(); // 排除所有未连接的网卡 QNetworkInterface tmpNet = ipDevList.at(i); QNetworkInterface::InterfaceFlags interFlags; interFlags = tmpNet.flags(); if(!((interFlags&QNetworkInterface::IsUp) && (interFlags&QNetworkInterface::IsRunning) && (interFlags&QNetworkInterface::CanBroadcast) && (interFlags&QNetworkInterface::CanMulticast) && !(interFlags&QNetworkInterface::IsLoopBack))) { continue; } QString tmpIp; for (int y=0; y<tmpIPlist.size(); ++y) { QNetworkAddressEntry xx = tmpIPlist.at(y); if (xx.ip() != QHostAddress::LocalHost && xx.ip().toIPv4Address() ) { ipReady = true; tmpIp = xx.ip().toString(); break; } } if( true == ipReady ) { ipList << tmpIp + " (" + ipDevList.at(i).humanReadableName() + ")"; if( tmpIp == lastUdpIp ) { autoLinkIpSeqInList = ipInc; } ipInc++; } } qDebug() << "ipList:" << ipList; |
在TCP SERVER中获取CLIENT的IP及端口
1 2 3 4 5 6 7 |
//clientIP = tcpSocket->peerAddress().toString(); // 网上的这种方法不可用,会多出来一些字符 quint32 ipv4 = tcpSocket->peerAddress().toIPv4Address(); char xx[30]; sprintf(xx, "%d.%d.%d.%d",ipv4>>24,(ipv4>>16)&0xFF,(ipv4>>8)&0xFF ,ipv4&0xFF); clientIP = xx; clientPort = tcpSocket->peerPort(); |