参考
Qt网路与通信(获取本机IP、MAC、IPV6子网掩码等网络信息)+ 源码
主要代码
QString strHostName = QHostInfo::localHostName();//本地主机名
QString strHostDomain = QHostInfo::localDomainName();//本地域名
qInfo() <<tr("本地域名:")+strHostDomain;
m_ptrLineEditHostName->setText(strHostName);
QHostInfo hostInfo = QHostInfo::fromName(strHostName);
qInfo() <<tr("addresses:");
//在windows系统中可以获取全部的IP地址,但是在linux中仅能获取一个ip地址且ip地址为127.0.0.1
//获取的ip地址可以在/etc/hosts中查到。
QList<QHostAddress> list = hostInfo.addresses();
foreach (auto item, list) {
qInfo() <<item.toString();
}
qInfo() <<tr("----------------------------------------------------------");
qInfo() <<tr("listAddress:");
QList<QHostAddress> listAddress = QNetworkInterface::allAddresses();//获取本机所有IP
foreach (auto item, listAddress) {
qInfo() <<item.toString();
}
QList<QNetworkInterface> listNetworkInterface=QNetworkInterface::allInterfaces();//获取所有的网络接口
qInfo() <<tr("----------------------------------------------------------");
foreach (auto item, listNetworkInterface) {
qInfo() << tr("网口设备:") + item.name();
qInfo() << tr("硬件地址:") + item.hardwareAddress();
foreach (auto item2, item.addressEntries()) {
qInfo() << " " + tr("ip地址:") + item2.ip().toString();
qInfo() << " " + tr("子网掩码:") + item2.netmask().toString();
qInfo() << " " + tr("广播地址:") + item2.broadcast().toString();
}
}