getHostInformation()获得主机信息,包括主机名,所有IP地址。
slotDetail()获得与网络接口相关的信息,包括IP地址,子网掩码,广播地址。
.pro
QT += network
networkinformation.h
#include "networkinformation.h"
NetworkInformation::NetworkInformation(QWidget *parent):QWidget(parent)
{
hostLabel = new QLabel(tr("主机名:"));
LineEditLocalHostName = new QLineEdit;
ipLabel = new QLabel(tr("IP 地址"));
LineEditAddress = new QLineEdit;
detailBtn = new QPushButton(tr("详细"));
mainLayout = new QGridLayout;
mainLayout->addWidget(hostLabel, 0, 0);
mainLayout->addWidget(LineEditLocalHostName, 0, 1);
mainLayout->addWidget(ipLabel, 1, 0);
mainLayout->addWidget(LineEditAddress, 1, 1);
mainLayout->addWidget(detailBtn, 2, 0, 1, 2);
getHostInformation();
connect(detailBtn, SIGNAL(clicked()), this, SLOT(slotDetail()));
}
NetworkInformation::~NetworkInformation()
{
}
void NetworkInformation::getHostInformation()
{
QString localHostName = QHostInfo::localHostName(); //获取主机名
LineEditLocalHostName->setText(localHostName);
QHostInfo hostInfo = QHostInfo::fromName(localHostName); //根据主机名来获取本机的信息
QList<QHostAddress> listAddress = hostInfo.addresses(); //获取本机所有ip地址
if(!listAddress.isEmpty())
LineEditAddress->setText(listAddress.first().toString());
}
void NetworkInformation::slotDetail()
{
QString detail = "";
QList<QNetworkInterface> list = QNetworkInterface::allInterfaces(); //获取所有网络接口的列表
for(int i=0; i<list.count(); i++)
{
QNetworkInterface interface = list.at(i);
detail = detail + tr("设备:") + interface.name() + "\n";
//获取IP地址条目列表,每个条目中包含一个IP地址,一个子网掩码和一个广播地址
QList<QNetworkAddressEntry> entryList = interface.addressEntries();
for(int j=0; j<entryList.count(); j++)
{
QNetworkAddressEntry entry = entryList.at(j);
detail = detail + "\t" + tr("IP地址:") + entry.ip().toString() + "\n";
detail = detail + "\t" + tr("子网掩码:") + entry.netmask().toString() + "\n";
detail = detail + "\t" + tr("广播地址:") + entry.broadcast().toString() + "\n";
}
}
QMessageBox::information(this, tr("Detail"), detail);
}
main.cpp
#include "networkinformation.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
NetworkInformation w;
w.show();
return a.exec();
}