Qt-网络与通信-获取本机网络信息

在网络应用中,经常需要获取本机主机名和IP地址和硬件地址等信息。运用QHostInfo、QNetworkInterface、QNetworkAddressEntry可以获得本机的网络信息。


上运行截图

Qt-网络与通信-获取本机网络信息_第1张图片



这里需要注意的,在Qt5.80 VS的版本中,有的字符“:”中文版本的,会导致编译错误。

第一步,需要再pro文件中加入 QT+= network


.h文件

#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

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 
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 listAddress = hostInfo.addresses();

    qDebug()<setText(listAddress.at(4).toString());
    }
}

void Widget::slotDetail()
{
    QString detail="";
    QList list=QNetworkInterface::allInterfaces();
    //(a)
    for(int i=0;i entryList=interface.addressEntries();
        //(d)
        for(int j=1;j


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





你可能感兴趣的:(Qt,QML)