使用qt的hostInfo类,查看本机的IP和设备

时间:2023-03-09 00:01:50
使用qt的hostInfo类,查看本机的IP和设备

创建NetWorkInformation类,main.cpp直接生成。

 #include "networkinformation.h"
#include <QApplication> int main(int argc, char *argv[])
{
QApplication a(argc, argv);
NetworkInformation w;
w.show(); return a.exec();
}

头文件声明要写的槽函数,还有布局控件。

 #ifndef NETWORKINFORMATION_H
#define NETWORKINFORMATION_H #include <QWidget>
#include <QHostInfo>
#include <QNetworkInterface>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QGridLayout>
class NetworkInformation : public QWidget
{
Q_OBJECT public:
NetworkInformation(QWidget *parent = );
~NetworkInformation();
public:
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 <QMessageBox>
NetworkInformation::NetworkInformation(QWidget *parent)
: QWidget(parent)
{
hostLabel = new QLabel("name:");
LineEditLocalHostname = new QLineEdit;
ipLabel = new QLabel(tr("ip:"));
LineEditAddress = new QLineEdit;
detailBtn = new QPushButton(tr("detail"));
mainLayout =new QGridLayout(this); mainLayout->addWidget(hostLabel,,);
mainLayout->addWidget(LineEditLocalHostname,,);
mainLayout->addWidget(ipLabel,,);
mainLayout->addWidget(LineEditAddress,,);
mainLayout->addWidget(detailBtn,,,,);
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); foreach (const QHostAddress &address, hostinfo.addresses())
{ if (address.protocol() == QAbstractSocket::IPv4Protocol)
{
LineEditAddress->setText((address.toString()));
}
}
}
void NetworkInformation::slotDetail()
{
QString detail="";
QList<QNetworkInterface>list=QNetworkInterface::allInterfaces();
for(int i=;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 =;j<entryList.count();j++)
{
/QNetworkAddressEntry entry = entryList.at(i);
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);
}