cpp
QString getIPAddr()
{
QStringList ips;
QList<QNetworkInterface> networkinterfaces = QNetworkInterface::allInterfaces();
foreach (QNetworkInterface interface, networkinterfaces)
{
QNetworkInterface::InterfaceFlags t_interFlags = interface.flags();
if(t_interFlags & QNetworkInterface::IsUp && t_interFlags & QNetworkInterface::IsRunning)
{
foreach (QNetworkAddressEntry entry, interface.addressEntries())
{
if (entry.ip() != QHostAddress::LocalHost&& entry.ip().protocol() == QAbstractSocket::IPv4Protocol)
{
ips.append(entry.ip().toString());
}
}
}
}
return ips.join("|");
}
上述函数返回本机所有IPv4的ip地址列表,比如192.168.1.10|192.166.1.95
其它方法=》
cpp
#if 0
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();
#endif
#if 0
QString hostNme = QHostInfo::localHostName();
QHostInfo hostInfo = QHostInfo::fromName(hostNme);
auto addList = hostInfo.addresses();
QString ipAddr = "IpList:";
if (!addList.isEmpty())
{
for (int i = 0;i < addList.count();++i)
{
QHostAddress hostAddress = addList.at(i);
ipAddr += hostAddress.toString();
if(i < addList.count() - 1)
ipAddr += ",";
}
}
#endif
获取客户端IP地址:
cpp
//获取对方的IP和端口
QString strSrcIp = pTcpSocket->peerAddress().toString();
if (pTcpSocket->peerAddress().protocol() == QAbstractSocket::IPv6Protocol && strSrcIp.startsWith("::ffff:"))
{
quint32 ipv4 = QHostAddress(strSrcIp.mid(7)).toIPv4Address();
strSrcIp = QHostAddress(ipv4).toString(); // IPv4地址: 192.168.0.1
}