1、在 .pro文件中加入 QT += network
2、在ui界面中画出界面,注意命名
代码部分:
networkinformation.h
#ifndef NETWORKINFORMATION_H
#define NETWORKINFORMATION_H
#include <QWidget>
#include <QHostInfo>
#include <QNetworkInterface>
QT_BEGIN_NAMESPACE
namespace Ui { class networkinformation; }
QT_END_NAMESPACE
class networkinformation : public QWidget
{
Q_OBJECT
public:
networkinformation(QWidget *parent = nullptr);
~networkinformation();
void getHostInformation(); //成员函数
public slots:
void slotDetail(); //槽函数
private:
Ui::networkinformation *ui;
};
#endif // NETWORKINFORMATION_H
networkinformation.cpp
#include "networkinformation.h"
#include "ui_networkinformation.h"
#include<QMessageBox>
networkinformation::networkinformation(QWidget *parent)
: QWidget(parent)
, ui(new Ui::networkinformation)
{
ui->setupUi(this);
getHostInformation();
connect(ui->detailBtn,SIGNAL(clicked()),this,SLOT(slotDetail()));
}
void networkinformation::getHostInformation()
{
QString localHostName = QHostInfo::localHostName();
ui->lineEditLocalHostName->setText(localHostName);
QHostInfo hostinfo = QHostInfo::fromName(localHostName);
//获取主机的IP地址列表
QList<QHostAddress> listAddress = hostinfo.addresses();
if(!listAddress.isEmpty())
{
ui->lineEditAddress->setText(listAddress.at(1).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();
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);
}
networkinformation::~networkinformation()
{
delete ui;
}
main.cpp不做修改
效果展示:
注意:
at(0)得到无线网卡IPv6地址
at(1)得到无限网卡IPv4地址
at(2)得到有线网卡IPv6地址
at(3)得到有限网卡IPv4地址
注意:at()可能越界