新手一枚,参考别的博客写了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);
}
不过获得的信息好像有点问题