Qt - 获取本机网络信息

目的:

  获取本机的主机名、IP地址、硬件地址等网络信息。

工具:

  使用Qt提供的网络模块QtNetwork(pro文件里面加network);

  使用Qt提供的类QHostInfo、QNetworkInterface、QNetworkAddressEntry。

代码:

  获取本机主机名和IP地址

void NetworkInformation::getHostInformation() {  
    //获取本机主机名  
    QString localHostName = QHostInfo::localHostName();  
    LineEditLocalHostName->setText(localHostName);  
  
    //通过本机主机名获取IP地址  
    QHostInfo hostInfo = QHostInfo::fromName(localHostName);  
    QList<QHostAddress> listAddress = hostInfo.addresses();  
    if(!listAddress.isEmpty()) {  
        LineEditAddress->setText(listAddress.first().toString());  
    }  
}  

 

  获取本机更加详细的信息

void NetworkInformation::slotDetail() {
    QString detail = "";

    //获取主机IP地址和网络接口列表
    QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();
    for(int i = 0; i < list.count(); i++) {
        QNetworkInterface interface = list.at(i);

        //获取网络接口名称
        detail = detail + tr("设备:") + interface.name() + "\n";
        //获取网络接口的硬件地址
        detail = detail + tr("硬件地址:") + interface.hardwareAddress() + "\n";

        //获取网络接口对应的IP地址(IPv4和IPv6)、子网掩码、广播地址
        QList<QNetworkAddressEntry> entryList = interface.addressEntries();
        for(int j = 0; j < entryList.count(); j++) {
            QNetworkAddressEntry entry = entryList.at(j);
            detail = detail + "\t" + tr("IP 地址:") + entry.ip().toString() + "\n";
            detail = detail + "\t" + tr("子网掩码:") + entry.netmask().toString() + "\n";
            detail = detail + "\t" + tr("广播地址:") + entry.broadcast().toString() + "\n";
        } 
    }
    QMessageBox::information(this, tr("Detail"), detail);
}

  

posted @ 2019-11-07 14:38  Citrusliu  阅读(470)  评论(0编辑  收藏  举报