注意要在.pro中添加
QT += network
1、通过QHostInfo获取主机名,在通过主机名可以获取ip
2、通过QNetworkInterface可以获取本机的所有网络接口,即可以获取接口中的name,hardware address
3、又可以通过网络接口获取网络地址如IP,NETMASK等,即QNetworkInterface的成员函数addressEntries()地址入口函数;
其还回值为QList<QNetworkAddressEntry> 那么就可以获取各类地址了!
如截图:
#ifndef NETWORKINFORMATION_H #define NETWORKINFORMATION_H #include <QDialog> class QLabel; class QLineEdit; class NetworkInformation: public QDialog { Q_OBJECT private: QLabel *nameLabel; QLabel *ipLabel; QLineEdit *nameEdit; QLineEdit *ipEdit; QPushButton *detailButton; public: NetworkInformation(QWidget *parent = 0); private slots: void slotDetail(); }; #endif // NETWORKINFORMATION_H
#include "networkinformation.h" #include <QtGui> #include <QHostInfo> #include <QNetworkInterface> NetworkInformation::NetworkInformation(QWidget *parent) : QDialog(parent) { nameLabel = new QLabel(tr("Name:")); nameEdit = new QLineEdit; nameLabel->setBuddy(nameEdit); nameEdit->setReadOnly(true); QString name = QHostInfo::localHostName(); nameEdit->setText(name); ipLabel = new QLabel(tr("Ip:")); ipEdit = new QLineEdit; ipLabel->setBuddy(ipEdit); ipEdit->setReadOnly(true); QHostInfo hostInfo = QHostInfo::fromName(name); QList<QHostAddress> listAddress = hostInfo.addresses(); if(!listAddress.empty()) ipEdit->setText(listAddress.first().toString()); detailButton = new QPushButton(tr("Detail")); connect(detailButton, SIGNAL(clicked()), this, SLOT(slotDetail())); QHBoxLayout *layout1 = new QHBoxLayout; layout1->addWidget(nameLabel); layout1->addWidget(nameEdit); QHBoxLayout *layout2 = new QHBoxLayout; layout2->addWidget(ipLabel); layout2->addWidget(ipEdit); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addLayout(layout1); mainLayout->addLayout(layout2); mainLayout->addWidget(detailButton); setLayout(mainLayout); setWindowTitle(tr("Local Host Information")); } //private slots void NetworkInformation::slotDetail() { QString detail = ""; QList<QNetworkInterface> listNetwork = QNetworkInterface::allInterfaces(); for(int i = 0; i < listNetwork.count(); i++) { detail += "name: " + listNetwork.at(i).name() + "\n"; detail += "hardware address: " + listNetwork.at(i).hardwareAddress() + "\n"; QList<QNetworkAddressEntry> listAddress = listNetwork.at(i).addressEntries(); for(int j = 0; j < listAddress.count(); j++) { detail += "ip: " + listAddress.at(j).ip().toString() + "\n"; detail += "netmask: " + listAddress.at(j).netmask().toString() + "\n"; detail += "broadcase: " + listAddress.at(j).broadcast().toString() + "\n"; } } QMessageBox::warning(this, tr("Detail"), detail); }
#include "networkinformation.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication app(argc, argv); NetworkInformation *network = new NetworkInformation; network->show(); return app.exec(); }