用Qt5实现的简单程序,获取本机网络信息。
建立工程后,在.pro里加入:
QT += network
用Qt设计器创建界面:
在widget.h中声明getHostInformation类:
public:
int getHostInformation();
声明槽函数:
public slots :
void slotDetail();
并包含头文件:
#include <QHostInfo>
#include <QNetworkInterface>
在widget.cpp中实现:
int Widget::getHostInformation()
{
QString localHostName = QHostInfo::localHostName();
ui->lineEditLocalHostName->setText(localHostName);QHostInfo hostinfo = QHostInfo::fromName(localHostName);
QList<QHostAddress> listAddress = hostinfo.addresses();
if(!listAddress.isEmpty())
{
ui->lineEditAddress->setText(listAddress.first().toString());
}
return 0;
}void Widget::slotDetail()
{
QString detail = "";
QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();
for(int i=0;i<list.count();i++)
{
QNetworkInterface interface = list.at(i);
detail = detail + tr("Device: ") + interface.name() + "\n";
detail = detail + tr("Hardware address: ") + interface.hardwareAddress() + "\n";
QList<QNetworkAddressEntry> entryList = interface.addressEntries();
for(int j=0;j<entryList.count();j++)
{
QNetworkAddressEntry entry = entryList.at(j);
detail = detail + "\t" + tr ("IP address: ") + entry.ip().toString() + "\n";
detail = detail + "\t" +tr ("Subnet mask: ") + entry.netmask().toString() + "\n";
detail = detail + "\t" +tr ("Broadcast address: ") + entry.broadcast().toString() + "\n";
}
}
QMessageBox::information(this,tr("Detail"),detail);
}
编译运行:
Moran at 2014.6.1