QT获取本机网络信息

1、在 .pro文件中加入 QT += network
2、在ui界面中画出界面,注意命名
在这里插入图片描述
代码部分:
networkinformation.h

#ifndef NETWORKINFORMATION_H
#define NETWORKINFORMATION_H

#include <QWidget>
#include <QHostInfo>
#include <QNetworkInterface>

QT_BEGIN_NAMESPACE
namespace Ui { class networkinformation; }
QT_END_NAMESPACE

class networkinformation : public QWidget
{
    Q_OBJECT

public:
    networkinformation(QWidget *parent = nullptr);
    ~networkinformation();

    void getHostInformation();  //成员函数

public slots:
    void slotDetail();   //槽函数

private:
    Ui::networkinformation *ui;
};
#endif // NETWORKINFORMATION_H

networkinformation.cpp

#include "networkinformation.h"
#include "ui_networkinformation.h"
#include<QMessageBox>
networkinformation::networkinformation(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::networkinformation)
{
    ui->setupUi(this);


    getHostInformation();

    connect(ui->detailBtn,SIGNAL(clicked()),this,SLOT(slotDetail()));
}
void networkinformation::getHostInformation()
{
    QString localHostName = QHostInfo::localHostName();
    ui->lineEditLocalHostName->setText(localHostName);
    QHostInfo hostinfo = QHostInfo::fromName(localHostName);

    //获取主机的IP地址列表
    QList<QHostAddress> listAddress = hostinfo.addresses();
    if(!listAddress.isEmpty())
    {
        ui->lineEditAddress->setText(listAddress.at(1).toString());
    }
}

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

    for(int i=0;i<list.count();i++)
    {
        QNetworkInterface interface = list.at(i);
        detail = detail +tr("设备:")+interface.name()+'\n';

        detail =detail +tr("硬件地址:")+interface.hardwareAddress()+'\n';

        QList<QNetworkAddressEntry> entryList = interface.addressEntries();

        for(int j=1;j<entryList.count();j++)
        {
            QNetworkAddressEntry entry = entryList.at(j);
            detail = detail+"\t" + tr("ip地址")+entry.ip().toString()+'\n';
            detail = detail +"\t"+tr("子网掩码:")+entry.netmask().toString()+"\n";
            detail = detail +"\t"+tr("广播地址")+entry.broadcast().toString()+"\n";
        }
    }
    QMessageBox::information(this,tr("Detail"),detail);

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


main.cpp不做修改

效果展示:
在这里插入图片描述
注意:
at(0)得到无线网卡IPv6地址
at(1)得到无限网卡IPv4地址
at(2)得到有线网卡IPv6地址
at(3)得到有限网卡IPv4地址

注意:at()可能越界

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值