天天看點

Qt-網絡與通信-擷取本機網絡資訊

在網絡應用中,經常需要擷取本機主機名和IP位址和硬體位址等資訊。運用QHostInfo、QNetworkInterface、QNetworkAddressEntry可以獲得本機的網絡資訊。

上運作截圖

Qt-網絡與通信-擷取本機網絡資訊

這裡需要注意的,在Qt5.80 VS的版本中,有的字元“:”中文版本的,會導緻編譯錯誤。

第一步,需要再pro檔案中加入 QT+= network

.h檔案

#ifndef WIDGET_H
#define WIDGET_H

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

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);
    ~Widget();
    void getHostInformation();
public slots:
    void slotDetail();
private:
    QLabel *hostLabel;
    QLineEdit *LineEditLocalHostName;
    QLabel *ipLabel;
    QLineEdit *LineEditAddress;
    QPushButton *detailBtn;
    QGridLayout *mainLayout;
};

#endif // WIDGET_H           

.cpp檔案

#include "widget.h"
#include <QDebug>
Widget::Widget(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()));
}

Widget::~Widget()
{

}

void Widget::getHostInformation()
{
    QString localHostName = QHostInfo::localHostName();			
    LineEditLocalHostName->setText(localHostName);
    QHostInfo hostInfo = QHostInfo::fromName(localHostName);	
  
    QList<QHostAddress> listAddress = hostInfo.addresses();

    qDebug()<<listAddress;
    if(!listAddress.isEmpty())									
    {
        LineEditAddress->setText(listAddress.at(4).toString());
    }
}

void Widget::slotDetail()
{
    QString detail="";
    QList<QNetworkInterface> list=QNetworkInterface::allInterfaces();
    //(a)
    for(int i=0;i<list.count();i++)
    {
        QNetworkInterface interface=list.at(i);
        detail=detail+tr("裝置:")+interface.name()+"\n";
        //(b)
        detail=detail+tr("硬體位址:")+interface.hardwareAddress()+"\n";
        //(c)
        QList<QNetworkAddressEntry> entryList=interface.addressEntries();
        //(d)
        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);
}           

工程位址:https://gitee.com/DreamLife-Technology_DreamLife/NetworkInformation

繼續閱讀