//获取本机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; }