QT获取本机网络信息

QT获取本机网络信息

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 

QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
    void getinformation();

private slots:
    void on_pushButton_info_clicked();

private:
    Ui::Widget *ui;
};
#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include
#include
#include
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    getinformation();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_info_clicked()
{
    QString detail = "";
    QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();

    for(int i=0;i<list.count();++i)
    {
        QNetworkInterface interface = list.at(i);
        detail+=tr("设备:")+interface.name()+"\n";
        detail+=tr("硬件地址:")+interface.hardwareAddress()+"\n";
        QList<QNetworkAddressEntry> entryList = interface.addressEntries();
        for(int j=1;j<entryList.count();++j)
        {
            QNetworkAddressEntry entry =  entryList.at(j);
            detail+=tr("\t")+tr("IP 地址:")+entry.ip().toString()+"\n";
            detail+=tr("\t")+tr("子网掩码")+entry.netmask().toString()+"\n";
            detail+=tr("\t")+tr("广播地址")+entry.broadcast().toString()+"\n";
        }

    }
    QMessageBox::information(this , tr("Detail") , detail);

}

void Widget::getinformation()
{
    QString localHostName = QHostInfo::localHostName();
    ui->lineEdit_name->setText(localHostName);

    QHostInfo hostInfo = QHostInfo::fromName(localHostName);
    QList<QHostAddress> listAdress = hostInfo.addresses();
    if(!listAdress.empty())
    {
        ui->lineEdit_ip->setText(listAdress.at(1).toString());
    }

}

结果如下
QT获取本机网络信息_第1张图片

你可能感兴趣的:(【QT】,qt)