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

1.pro文件加入
QT       += network
2.添加头文件
#include 
#include 
#include 
#include 
    //获取主机名
    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 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()<
//获取计算机详细信息
void slotDetail()  
{  
    QString detail="";  
    QList list=QNetworkInterface::allInterfaces();  
    for(int i=0;i entryList=interface.addressEntries();  
        for(int j=0;j


参考文档:

Qt之获取本机网络信息









你可能感兴趣的:(QT)