主要使用到的类有:
QHostInfo
QHostAddress
QNetworkInterface
QNetworkAddressEntry
//QHostInfo类作用,获取主机名,也可以通过主机名来查找IP地址,或者通过IP地址来反向查找主机名。
QString localHostName = QHostInfo::localHostName();
qDebug() << "LocalHostName:" << localHostName;
//获取IP地址
QHostInfo info = QHostInfo::fromName(localHostName);
qDebug() << "IP Address:" << info.addresses();
foreach(QHostAddress address, info.addresses())
{
if (address.protocol() == QAbstractSocket::IPv4Protocol)
qDebug() << "IPv4 Address:" << address.toString();
}
foreach (QHostAddress address, QNetworkInterface::allAddresses())
{
qDebug() << "Address:" << address;
}
3.获取设备名、MAC地址、子网掩码、广播地址等
//获取所有网络接口的列表
foreach (QNetworkInterface netInterface, QNetworkInterface::allInterfaces())
{
//设备名
qDebug() << "Device:" << netInterface.name();
//MAC地址
qDebug() << "HardwareAddress:" << netInterface.hardwareAddress();
QList entryList = netInterface.addressEntries();
//遍历每一个IP地址(每个包含一个IP地址,一个子网掩码和一个广播地址)
foreach(QNetworkAddressEntry entry, entryList)
{
//IP地址
qDebug() << "IP Address:" << entry.ip().toString();
//子网掩码
qDebug() << "Netmask:" << entry.netmask().toString();
//广播地址
qDebug() << "Broadcast:" << entry.broadcast().toString();
}
}