获取所有活动网卡
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及端口
//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();
正文完