获得本机网络信息

评价:
0
(0用户)

1、头文件代码:

#ifndef NETWORKINFORMATION_H
#define NETWORKINFORMATION_H

#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QGridLayout>
#include <QMessageBox>

#include <QHostInfo>
#include <QNetworkInterface>

class NetworkInformation : public QWidget
{
Q_OBJECT

public:
NetworkInformation(QWidget *parent = nullptr);
~NetworkInformation();

void getHostInformation();

public slots:
void slotDetail();

private:
QLabel *hostLabel;
QLineEdit *localHostNameLineEdit;
QLabel *ipLabel;
QLineEdit *addressLineEdit;
QPushButton *detailBtn;
QGridLayout *mainLayout;
};
#endif // NETWORKINFORMATION_H

2、源文件代码:

#include “networkinformation.h”
#include <QtDebug>

NetworkInformation::NetworkInformation(QWidget *parent)
: QWidget(parent)
{
hostLabel = new QLabel(tr(“主机名:”));
localHostNameLineEdit = new QLineEdit;
ipLabel = new QLabel(tr(“IP 地址:”));
addressLineEdit = new QLineEdit;
detailBtn = new QPushButton(tr(“详细”));
mainLayout = new QGridLayout(this);
mainLayout->addWidget(hostLabel, 0, 0);
mainLayout->addWidget(localHostNameLineEdit, 0, 1);
mainLayout->addWidget(ipLabel, 1, 0);
mainLayout->addWidget(addressLineEdit, 1, 1);
mainLayout->addWidget(detailBtn, 2, 0, 1, 2);

getHostInformation(1);
connect(detailBtn, SIGNAL(clicked()), this, SLOT(slotDetail()));
}

NetworkInformation::~NetworkInformation()
{
}

void NetworkInformation::getHostInformation(int aaa)
{
// 获取本机主机名。QHostlnfo 提供了一系列有关网络信息的静态函数,
// 可以根据主机名获取分配的 IP 地址,也可以根据 IP 地址获取相应的主机名。
QString localHostName = QHostInfo::localHostName();
localHostNameLineEdit->setText(localHostName);
// 根据主机名获取相关主机信息,包括 1P 地址等
QHostInfo hostInfo = QHostInfo::fromName(localHostName);
// 获取主机的 IP 地址列表
QList<QHostAddress> listAddress = hostInfo.addresses();

for (int i = 0; i < listAddress.count(); ++i)
{
qDebug() << listAddress.at(i).toString();
}

// 获取的主机 IP 地址列表可能为空
// 在不为空的情况下,此例本机使用第四个 IP 地址
if (!listAddress.isEmpty())
{
addressLineEdit->setText(listAddress.at(3).toString());
}
}

void NetworkInformation::slotDetail()
{
QString detail = “”;
// 获取主机IP地址和网络接口的列表
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.name() + “\n”;

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);
}

本文为原创文章,转载请注明出处!

注册并通过认证的用户才可以进行评价!

发表评论