码迷,mamicode.com
首页 > 其他好文 > 详细

qt获取本机ip

时间:2017-12-11 11:18:42      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:ipv4   ipv6   network   ip地址   str   inter   tostring   protocol   list   

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

 

qt获取本机ip

标签:ipv4   ipv6   network   ip地址   str   inter   tostring   protocol   list   

原文地址:http://www.cnblogs.com/amwuau/p/8021770.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!