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

}

结果如下

相关推荐
Felix_One5 天前
Qt 串口通信避坑指南:QSerialPort 的 5 个常见问题
qt
blasit8 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
范特西.i13 天前
QT聊天项目(8)
开发语言·qt
枫叶丹413 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
十五年专注C++开发13 天前
Qt deleteLater作用及源码分析
开发语言·c++·qt·qobject
kangzerun13 天前
SQLiteManager:一个优雅的Qt SQLite数据库操作类
数据库·qt·sqlite
金刚狼8813 天前
qt和qt creator的下载安装
开发语言·qt
追烽少年x13 天前
Qt中使用Zint库显示二维码
qt
谁刺我心13 天前
qt源码、qt在线安装器镜像下载
开发语言·qt
金刚狼8813 天前
在qt creator中创建helloworld程序并构建
开发语言·qt