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

}

结果如下

相关推荐
zhanghaha131423 分钟前
Qt 工程实例:逐词逐句保姆级讲解
qt
架构师伯子明17 小时前
QT+OpenGL(3):FBO离屏渲染
开发语言·qt
mengzhi啊20 小时前
把数据存入sql数据库。qt,c++。
数据库·sql·qt
mengzhi啊1 天前
SerialPortItem对串口再封装一层,省去一些常用的步骤,不用每次都去写类
qt
用户8334423966142 天前
从批量操作到任务中心,再到现场工作台:DeviceForge v2.10—v2.12 完整演进
qt
宛 禾2 天前
Qt 控件入门:QLabel 从拖拽到对象树,一篇讲透
c++·qt·学习
打工仔折腾 AI2 天前
Qt网络编程实战:UDP、TCP到HTTP的落地经验与选型
网络·人工智能·后端·python·qt·udp·ai agent 实战
Lhan.zzZ2 天前
Linux + Qt/QML:解决 QtQuick.VirtualKeyboard.Plugins 模块加载失败与环境变量配置
linux·数据库·qt
誰能久伴不乏2 天前
QT工业上位机一次「指令静默丢失」的排查
qt·docker·github
扶尔魔ocy3 天前
【qt openGL入门笔记】OSG实现飞机模型在网格图上飞行并进行态势标绘(四)
qt·opengl·osg