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
其它方法=》文章来源:https://www.toymoban.com/news/detail-626332.html
#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地址:文章来源地址https://www.toymoban.com/news/detail-626332.html
//获取对方的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
}
到了这里,关于Qt 获取本机 ip地址方法 获取客户端ip和端口的方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!