qt获取本机网络信息

networkinformation.h

#include<QtGui/QWidget>
#include<QLabel>
#include<QPushButton>
#include<QLineEdit>
#include<QGridLayout>
#include<QHostInfo>


class NetworkInformation:public QWidget
{
	Q_OBJECT
	
	public:
		NetworkInformation(QWidget *parent=0);
		void getHostInformation();
		//~NetworkInformation();
	
	public slots:
		void slotDetail();

	private:
		QLabel *hostLabel;
		QLineEdit *LineEditLocalHostName;
		QLabel *ipLabel;
		QLineEdit *LineEditAddress;
		QPushButton *detailBtn;
		QGridLayout *mainLayout;
};

networkinformation.cpp:

#include<QNetworkInterface>
#include<QMessageBox>
#include"networkinformation.h"


NetworkInformation::NetworkInformation(QWidget *parent)
	:QWidget(parent)
{
	hostLabel=new QLabel(tr("host:"));
	LineEditLocalHostName=new QLineEdit;
	ipLabel=new QLabel(tr("IP:"));
	LineEditAddress=new QLineEdit;

	detailBtn=new QPushButton(tr("details"));

	mainLayout=new QGridLayout(this);
	mainLayout->addWidget(hostLabel,0,0);
	mainLayout->addWidget(LineEditLocalHostName,0,1);
	mainLayout->addWidget(ipLabel,1,0);
	mainLayout->addWidget(LineEditAddress,1,1);
	mainLayout->addWidget(detailBtn,2,0,1,2);

	getHostInformation();

	connect(detailBtn,SIGNAL(clicked()),this,SLOT(slotDetail()));
}


void NetworkInformation::getHostInformation()
{
	QString localHostName=QHostInfo::localHostName();
	LineEditLocalHostName->setText(localHostName);

	QHostInfo hostInfo=QHostInfo::fromName(localHostName);
	QList<QHostAddress> listAddress=hostInfo.addresses();

	if(!listAddress.isEmpty())
	{
		LineEditAddress->setText(listAddress.first().toString());
	}
}


void NetworkInformation::slotDetail()
{
	QString detail="";
	QList<QNetworkInterface> list=QNetworkInterface::allInterfaces();

	for(int i=0;i<list.count();i++)
	{
		QNetworkInterface interface=list.at(i);
		detail=detail+tr("shebei:")+interface.name()+"\n";
		QString hardwareAddress=interface.hardwareAddress();
		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("netmask:")+entry.netmask().toString()+"\n";
			detail=detail+"\t"+tr("broadcast:")+entry.broadcast().toString()+"\n";
		}
	}
	QMessageBox::information(this,tr("Detail"),detail);
}

main.cpp:

#include<QtGui/QApplication>
#include"networkinformation.h"
#include<QTextCodec>


int main(int argc, char *argv[])
{
	QApplication a(argc,argv);
	QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
	NetworkInformation w;
	w.show();
	return a.exec();
}


转载于:https://www.cnblogs.com/bzyzhang/p/5399626.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值