Qt获取计算机名、用户名、IP地址、MAC

这个硬件信息的获取需要使用到 network 模块

# 1. 在pro文件中添加 QT += network

# 需要用到的头文件
#include <QHostInfo> // 计算机名
#include <QStandardPaths>  // 用户名(获取家目录,删除其它字段只保留用户名)
#include <QNetworkInterface>  // 网卡信息


    cout << "当前计算机名:" << QHostInfo::localHostName();
    cout << "当前登陆用户:" << QStandardPaths::writableLocation(QStandardPaths::HomeLocation).section("/", -1, -1);

    QList<QHostAddress> AddressList = QNetworkInterface::allAddresses();
    foreach(QHostAddress address, AddressList){
        if(address.protocol() == QAbstractSocket::IPv4Protocol &&
                address != QHostAddress::Null &&
                address != QHostAddress::LocalHost){
            if (address.toString().contains("127.0.")){
                continue;
            }
            cout << "当前IP地址:" << address.toString();
            break;
        }
    }

    // ---> 依次输出系统中每张网卡的详细信息
    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=0;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);

posted @ 2022-01-24 10:03  看不见的R  阅读(651)  评论(0编辑  收藏  举报