程序
需要先加入网络模块:在.pro中加入QT+=network
.h
#ifndef NETWORKINFORMATION_H
#define NETWORKINFORMATION_H
#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QGridLayout>
#include <QMessageBox>
class NetworkInformation : public QWidget
{
Q_OBJECT
public:
NetworkInformation(QWidget *parent = 0);
~NetworkInformation();
void getHostInformation();
public slots:
void slotDetail();
private:
QLabel *hostLabel;
QLineEdit *LineEditLocalHostName;
QLabel *ipLabel;
QLineEdit *LineEditAddress;
QPushButton *detailBtn;
QGridLayout *mainLayout;
};
#endif // NETWORKINFORMATION_H
.cpp
#include "networkinformation.h"
#include <QHostInfo>
#include <QNetworkInterface>
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(this);
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);//根据主机名获得相关IP信息
QList<QHostAddress> listAddress =hostInfo.addresses();
if(!listAddress.isEmpty())
{
LineEditAddress->setText(listAddress.at(2).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";
detail=detail+tr("硬件地址:")+interface.hardwareAddress()+"\n";
QList<QNetworkAddressEntry>entryList=interface.addressEntries();//返回网络接口的IP地址和子网掩码、广播地址
for(int j=1;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);
}