Qt 获得ip小程序

新手一枚,参考别的博客写了vs+Qt 获得主机名与ip地址小程序,没有用Qt designer,那篇博客的代码运行有点问题,就改了一下。
原文https://blog.csdn.net/a19990412/article/details/82886249
只有ip.h与ip.cpp两个代码文件,ui_ip.h编译后会自动生成,main.cpp就用建QtGui工程自带的。
ip.h

#pragma once
#pragma comment(lib,"Qt5Networkd.lib")
#pragma execution_character_set("utf-8")
#include <QtWidgets/QMainWindow>
#include "ui_ip.h"
#include <QLabel>
#include <QPushButton>
#include <QGridLayout>
#include <QLineEdit>
#include <QMessageBox>
#include <QtNetwork\QHostInfo>
#include <QtNetwork\QNetworkInterface>
class ip : public QMainWindow
{
	Q_OBJECT
public:
	ip(QWidget *parent = Q_NULLPTR);
	void gethostinformation();
private slots:
	void slotdetail();
private:
	Ui::ipClass ui;
	QLabel *hostlabel;
	QLineEdit *hostline;
	QPushButton *detailbtn;
	QMessageBox *detailmsg;
	QGridLayout *mainlayout;
};

ip.cpp

#include "ip.h"
ip::ip(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	hostlabel = new QLabel("主机名");
	hostline = new QLineEdit;
	detailbtn = new QPushButton("detail");
	detailmsg = new QMessageBox;
	mainlayout = new QGridLayout(ui.centralWidget);
	mainlayout->addWidget(hostlabel, 0, 0);
	mainlayout->addWidget(hostline, 0, 1);
	mainlayout->addWidget(detailbtn,1,0,1,2);
	gethostinformation();
	connect(detailbtn, SIGNAL(clicked()), this, SLOT(slotdetail()));
}
void ip::gethostinformation()
{
	QString localHostName = QHostInfo::localHostName(); //得到主机名
	hostline->setText(localHostName);
}
void ip::slotdetail()
{
	QString detailstr = "";
	QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();
	//返回主机上的所有的网络接口的列表
	foreach (QNetworkInterface interface ,list)
	{
		detailstr += "设备:" + interface.name() + "\n";
		detailstr += "地址:" + interface.hardwareAddress() + "\n";
		QList<QNetworkAddressEntry> entryList = interface.addressEntries();
		//获取IP地址条目列表,每个条目中包含一个IP地址,一个子网掩码和一个广播地址
		foreach(QNetworkAddressEntry entry, entryList)
		{
			detailstr += "ip地址:" + entry.ip().toString() + "\n";
			detailstr += "子网掩码:" + entry.netmask().toString() + "\n";
			detailstr += "广播地址:" + entry.broadcast().toString() + "\n";
			detailstr += "\n";
		}
	}
	QMessageBox::information(this, "detail", detailstr);
}

不过获得的信息好像有点问题
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值