参考Qt的文档可以看出:
[static] QList QNetworkInterface::allAddresses()
This convenience function returns all IP addresses found on the host machine. It is equivalent to calling addressEntries() on all the objects returned by allInterfaces() that are in the QNetworkInterface::IsUp state to obtain lists of QNetworkAddressEntry objects then calling QNetworkAddressEntry::ip() on each of these.
其意思是:该函数可以返回所有在主机上可以发现的IP地址。它等同于对addressEntries() 函数中每个元素调用addressEntries(),然后调用返回的值中所有元素的QNetworkAddressEntry::ip() 函数。
即:

auto mmmmm = QNetworkInterface::allInterfaces();
mmmmm.at(0).addressEntries().at(0).ip().toString();

但是如果只是得到IP地址的话,不用上面这么麻烦,直接用
allAddresses()函数即可。

QList<QHostAddress> allIP = QNetworkInterface::allAddresses();

该函数返回一个list里面是所有关于QHostAddress类的对象,其中每两个元素是一组,先是MAC地址后面的是IP地址。
如果只想获取本机所有的IP地址而不获取网卡物理地址,那么就用下面的代码即可实现。将所有的IP地址放在一个字符串中并独行存在。

auto allIP = QNetworkInterface::allAddresses();
QString str_IP;
for (uint8_t index = 1; index < allIP.size();index+=2) 
{
     str_IP += allIP.at(index).toString() + "\n";
}
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐