在学习Qt,想尝试一下用Qt获取IP地址和名称,代码如下:
QLabel *label = new QLabel(this);
QString localName = QHostInfo::localHostName();
label->setGeometry(QRect(50,50,200,40));
label->setText("PC-Name: "+localName);
QLabel *label_IP = new QLabel(this);
label_IP->setGeometry(QRect(50,100,200,40));
QHostInfo info = QHostInfo::fromName(localName);
//遍历地址获取IPV4地址
foreach(QHostAddress address,info.addresses())
{
if(address.protocol()==QAbstractSocket::IPv4Protocol)
{
label_IP->setText("IP: "+address.toString());
}
}
需添加头文件如下:
#include <QtNetwork/QHostInfo>
#include <QLabel>
运行结果