最重要的一步,先在工程pro文件添加 QT += network
用到头文件
QHostInfo
QNetworkInterface
函数: (只写出返回类型,没有具体到是否const
QHostInfo
QHostInfo::localHostName(); 静态函数,获取主机名
QHostInfo::fromName(hostName); 静态函数,通过主机名获取一个HostInfo对象
QList<QHostAddress> addresses(); 返回一个HostAddress列表
QHostAddress
hostAddress.toString(); 将地址作为str返回
QNetworkInterface
QList<QNetworkAddressEntry> addressEntries(); 返回一个AddressEntry列表
QList<QHostAddress> allAddress(); 静态函数,返回一个HostAddress列表
QString name(); 返回设备名(网卡
QString hardwareAddress(); 返回硬件地址(MAC
QNetworkAddressEntry
entry.ip().toString(); 获取IP地址
entry.netmask().toString(); 获取子网掩码
entry.broadcast().toString(); 获取广播地址
例子效果:
代码:
槽函数
void NetInfoWidget::getLocalHostInfo()
{
//获取主机名
QString hostName = QHostInfo::localHostName();
this->setWindowTitle(hostName);
//通过主机名获取一个hostInfo对象
QHostInfo hostInfo = QHostInfo::fromName(hostName);
//获取一个address列表
QList<QHostAddress> list = hostInfo.addresses();
QString ipAddress = "";
for(int i = 0; i < list.length(); ++i){
//address.toString() 得到str格式的ip地址
ipAddress += list.at(i).toString() + "\n";
}
//获取一个interface列表,通过interface中的entry来获取信息
//在addRootNode函数中获取信息并设置treeWidget的内容(用于显示的控件为QTreeWiget
QList<QNetworkInterface> interfaceList = QNetworkInterface::allInterfaces();
foreach(QNetworkInterface interface , interfaceList){
addRootNode(&interface);
}
QMessageBox::information(this, "详细信息", ipAddress);
}
获取信息并给treeWidget添加节点
void NetInfoWidget::addRootNode(QNetworkInterface *interface)
{
QTreeWidgetItem * root = new QTreeWidgetItem(treeWidget);
//获取到设备名(网卡
root->setText(0,interface->name());
//获取硬件地址(MAC
root->setText(1,interface->hardwareAddress());
//拿到entry列表,获取entry对象中的信息
QList<QNetworkAddressEntry> entryList = interface->addressEntries();
foreach(QNetworkAddressEntry entry , entryList){
QTreeWidgetItem * ipAddressItem = new QTreeWidgetItem(root);
ipAddressItem->setText(0, "ip地址");
ipAddressItem->setText(1, entry.ip().toString());
QTreeWidgetItem * netMaskItem = new QTreeWidgetItem(root);
netMaskItem->setText(0, "子网掩码");
netMaskItem->setText(1, entry.netmask().toString());
QTreeWidgetItem * broadcastItem = new QTreeWidgetItem(root);
broadcastItem->setText(0, "广播地址");
broadcastItem->setText(1, entry.broadcast().toString());
}
}