QT如果要进行网络编程首先需要在.pro”中添加如下代码: QT += network 在头文件中包含相关头文件: #include <QHostInfo> #include <QNetworkInterface>
QHostInfo类用于获得主机信息。示范代码如下: QString localHostName = QHostInfo::localHostName(); QHostInfo hostInfo = QHostInfo::fromName(localHostName); QList<QHostAddress> list = hostInfo.addresses(); if(!list.isEmpty()) { QList<QHostAddress>::iterator i; for (i = list.begin();i != list.end();i++) QMessageBox::information(this,tr("提示"), (*i).toString()); }
QNetworkInterface类获得与网络接口相关的信息,具体实现代码如下: QString detail=""; QList<QNetworkInterface> list=QNetworkInterface::allInterfaces(); QList<QNetworkInterface>::iterator i; for (i = list.begin();i != list.end();i++) { QNetworkInterface interface=*i; detail=tr("设备:")+interface.name()+"\n"; detail=detail+tr("硬件地址:")+interface.hardwareAddress()+"\n"; QList<QNetworkAddressEntry> entryList=interface.addressEntries(); QList<QNetworkAddressEntry>::iterator j; for (j = entryList.begin();j != entryList.end();j++) { QNetworkAddressEntry entry=*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); }