Qt获取本机的IP地址、用户名等相关信息

时间:2022-05-27 08:36:41
1.pro文件加入
QT       += network
2.添加头文件
#include <QHostAddress>
#include <QHostInfo>
#include <QNetworkInterface>
#include <QProcess>
    //获取主机名
    QString localHost = QHostInfo::localHostName();
 
//获取用户名
QString getUserName()
{
#if 1
    QStringList envVariables;
    envVariables << "USERNAME.*" << "USER.*" << "USERDOMAIN.*"
                 << "HOSTNAME.*" << "DOMAINNAME.*";
    QStringList environment = QProcess::systemEnvironment();
    foreach (QString string, envVariables) {
        int index = environment.indexOf(QRegExp(string));
        if (index != -1) {
            QStringList stringList = environment.at(index).split('=');
            if (stringList.size() == 2) {
                return stringList.at(1);
                break;
            }
        }
    }
    return "unknown";
#else
    QString userName = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
    userName = userName.section("/", -1, -1);
    return userName;
#endif
}
//获取本机IP
QString getIP(QString localHost)
{
    QString ipAddr;
#if 0
    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;
            }
            ipAddr = address.toString();
            break;
        }
    }
#else
    QHostInfo info = QHostInfo::fromName(localHost);
    info.addresses();//QHostInfo的address函数获取本机ip地址
    //如果存在多条ip地址ipv4和ipv6:
    foreach(QHostAddress address,info.addresses())
    {
        if(address.protocol()==QAbstractSocket::IPv4Protocol){//只取ipv4协议的地址
            qDebug()<<address.toString();
            ipAddr = address.toString();
        }
    }
#endif
    return ipAddr;
}
//获取计算机详细信息
void 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=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);  
}


参考文档:

Qt之获取本机网络信息