QT获取本机网络信息

QT获取本机网络信息

widget.h

cpp 复制代码
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

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

cpp 复制代码
#include "widget.h"
#include "ui_widget.h"
#include<QHostInfo>
#include<QNetworkInterface>
#include<QMessageBox>
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());
    }

}

结果如下

相关推荐
ae_zr15 小时前
QT动态编译应用后,如何快速获取依赖
开发语言·qt
LYOBOYI12316 小时前
qml的对象树机制
c++·qt
菜鸟小芯17 小时前
Qt Creator 集成开发环境下载安装
开发语言·qt
牵牛老人20 小时前
Qt中集成 MQTT 来实现物联网通信:从原理到实战全解析
开发语言·qt·物联网
LYOBOYI12320 小时前
qml的布局策略
c++·qt
小小码农Come on1 天前
QT常用控件:QListWidget
开发语言·qt
侯孟禹1 天前
Gemini写的抠图工具
qt·opencv
空空空空空空空空空空空空如也1 天前
QT通过编译宏区分x86 linux arm的方法
linux·开发语言·qt
四维碎片1 天前
【Qt】UDP跨平台调试工具
qt·学习·udp
踏过山河,踏过海1 天前
【用ui文件做个简单工具的开发,为什么修改完ui后,程序重新编译运行后,GUI界面还是不变呢?】
qt·ui