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

}

结果如下

相关推荐
Source.Liu4 小时前
【QOwnNotes】概念架构说明
qt
世转神风-4 小时前
qt-通信协议基础-QStirng转QByteArray-进阶操作
qt
世转神风-6 小时前
qt-union-联合体基础讲解
开发语言·qt
这我可不懂6 小时前
谈谈mcp协议的实现
开发语言·qt·哈希算法
Source.Liu19 小时前
【QOwnNotes】QOwnNotes 介绍
qt
特立独行的猫a19 小时前
QT开发鸿蒙PC应用:环境搭建及第一个HelloWorld
开发语言·qt·harmonyos·环境搭建·鸿蒙pc
零小陈上(shouhou6668889)21 小时前
YOLOv8+PyQt5输电线路缺陷检测(目前最全面的类别检测,可以从图像、视频和摄像头三种路径检测)
python·qt·yolo
Larry_Yanan21 小时前
Qt多进程(五)QUdpSocket
开发语言·c++·qt·学习·ui
ht巷子1 天前
Qt:容器类的迭代
开发语言·c++·qt
byxdaz1 天前
Qt 中将 QWidget 改为模态的方法
qt