The Qt networking module provides us with classes for writing TCP/IP clients and servers. It provides lower-level classes such as QTcpSocket, QTcpServer, and QUdpSocket that represent low-level networking concepts, and higher-level classes such as QNetworkRequest, QNetworkReply, and QNetworkAccessManager to perform network operations using common protocols. It also provides classes such as QNetworkConfiguration, QNetworkConfigurationManager and QNetworkSession to implement bearer management.
To use the Qt network module in the program, we need to add the following statement in the pro project configuration file.
QT += network
Get the network information of this machine
Why get the local network information first? Before establishing network communication, we must at least obtain the IP address of the other party. In network applications, network information such as the host name, IP address, and MAC address of the machine is often needed. Usually, you can view the relevant information by calling out the command line cmd window in Windows and entering ipconfig or using the ifconfig command in the Linux system. Yes, here we use Qt to make an interface and functions that can be queried, laying a simple foundation for subsequent network programming.
Qt provides QHostInfo and QNetworkInterface classes that can be used for such information query. More functions related to QHostInfo and QNetworkInterface can be found in the Qt help documentation. Below we will use related functions when writing code, with clear comments.
Applications
Project purpose: Learn how to obtain information about all interfaces of the local network through the QHostInfo and QNetworkInterface classes.
Project name: networkhostinfo, to obtain the information of the local network interface.
Get the network interface information of the machine, print it on the text browser box, and click the button to get it directly. In order to clearly see that it is a re-acquisition process, in this example, click the Get Local Information button and delay for 1 second to refresh the obtained information. Click another clear text information button to clear the text content on the text browser box.
The code part added to the first line of the project file networkhostinfo.pro file is as follows.
QT += core gui network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
The specific code in the header file "mainwindow.h" is as follows.
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
#include <QTextBrowser>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QTimer>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
/* 点击获取和清空文本按钮 */
QPushButton *pushButton[2];
/* 文本浏览框用于显示本机的信息 */
QTextBrowser *textBrowser;
/* 水平Widget容器和垂直Widget容器*/
QWidget *hWidget;
QWidget *vWidget;
/* 水平布局和垂直布局 */
QHBoxLayout *hBoxLayout;
QVBoxLayout *vBoxLayout;
/* 定时器 */
QTimer *timer;
/* 获取本机的网络的信息,返回类型是QString */
QString getHostInfo();
private slots:
/* 定时器槽函数,点击按钮后定时触发 */
void timerTimeOut();
/* 显示本机信息 */
void showHostInfo();
/* 启动定时器 */
void timerStart();
/* 清空textBrowser的信息 */
void clearHostInfo();
};
#endif // MAINWINDOW_H
The header file mainly declares two buttons and a text browser box. In addition, there is a timer, which declares some slot functions, which is relatively simple. The specific code in the source file "mainwindow.cpp" is as follows.
#include "mainwindow.h"
#include <QNetworkInterface>
#include <QHostInfo>
#include <QThread>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
/* 设置位置与大小 */
this->setGeometry(0, 0, 800, 480);
/* 点击获取本地信息按钮和清空文本按钮 */
pushButton[0] = new QPushButton();
pushButton[1] = new QPushButton();
pushButton[0]->setText("获取本机信息");
pushButton[1]->setText("清空文本信息");
/* 按钮的大小根据文本自适应,
* 注意setSizePolicy需要在布局中使用 */
pushButton[0]->setSizePolicy(QSizePolicy::Fixed,
QSizePolicy::Fixed);
pushButton[1]->setSizePolicy(QSizePolicy::Fixed,
QSizePolicy::Fixed);
/* 水平Widget和垂直Widget用于添加布局 */
hWidget = new QWidget();
vWidget = new QWidget();
/* 水平布局和垂直布局 */
hBoxLayout = new QHBoxLayout();
vBoxLayout = new QVBoxLayout();
/* 文本浏览框 */
textBrowser = new QTextBrowser();
/* 添加到水平布局 */
hBoxLayout->addWidget(pushButton[0]);
hBoxLayout->addWidget(pushButton[1]);
/* 将水平布局设置为hWidget的布局 */
hWidget->setLayout(hBoxLayout);
/* 将文本浏览框和hWidget添加到垂直布局 */
vBoxLayout->addWidget(textBrowser);
vBoxLayout->addWidget(hWidget);
/* 将垂直布局设置为vWidget的布局 */
vWidget->setLayout(vBoxLayout);
/* 设置vWidget为中心部件 */
setCentralWidget(vWidget);
/* 定时器初始化 */
timer = new QTimer();
/* 信号槽连接 */
connect(pushButton[0], SIGNAL(clicked()),
this, SLOT(timerStart()));
connect(pushButton[1], SIGNAL(clicked()),
this, SLOT(clearHostInfo()));
connect(timer, SIGNAL(timeout()),
this, SLOT(timerTimeOut()));
}
MainWindow::~MainWindow()
{
}
void MainWindow::timerStart()
{
/* 清空文本 */
textBrowser->clear();
/* 定时1s */
timer->start(1000);
}
void MainWindow::timerTimeOut()
{
/* 显示本机信息 */
showHostInfo();
/* 停止定时器 */
timer->stop();
}
QString MainWindow::getHostInfo()
{
/* 通过QHostInfo的localHostName函数获取主机名称 */
QString str = "主机名称:" + QHostInfo::localHostName() + "\n";
/* 获取所有的网络接口,
* QNetworkInterface类提供主机的IP地址和网络接口的列表 */
QList<QNetworkInterface> list
= QNetworkInterface::allInterfaces();
/* 遍历list */
foreach (QNetworkInterface interface, list) {
str+= "网卡设备:" + interface.name() + "\n";
str+= "MAC地址:" + interface.hardwareAddress() + "\n";
/* QNetworkAddressEntry类存储IP地址子网掩码和广播地址 */
QList<QNetworkAddressEntry> entryList
= interface.addressEntries();
/* 遍历entryList */
foreach (QNetworkAddressEntry entry, entryList) {
/* 过滤IPv6地址,只留下IPv4 */
if (entry.ip().protocol() ==
QAbstractSocket::IPv4Protocol) {
str+= "IP 地址:" + entry.ip().toString() + "\n";
str+= "子网掩码:" + entry.netmask().toString() + "\n";
str+= "广播地址:" + entry.broadcast().toString() + "\n\n";
}
}
}
/* 返回网络信息 */
return str;
}
void MainWindow::showHostInfo()
{
/* 获取本机信息后显示到textBrowser */
textBrowser->insertPlainText(getHostInfo());
}
void MainWindow::clearHostInfo()
{
/* 判断textBrowser是否为空,如果不为空则清空文本 */
if (!textBrowser->toPlainText().isEmpty())
/* 清空文本 */
textBrowser->clear();
}
First, get the host name through the localHostName function of QHostInfo.
Then get the list of network interfaces through QNetworkInterface::allInterfaces(). The list class stores the IP address, subnet mask and broadcast address. If we use the qDebug() function to print out the list, we can find that all network information has been obtained. And we want to extract the network information in the network using QNetworkAddressEntry.
Then use QNetworkAddressEntry to use the function addressEntries() from the interface to get all the entries. You can use the object entry of QNetworkAddressEntry to get the IP address subnet mask and broadcast address.
Because the obtained entries may have two IPs under one QNetworkInterface, namely ipv4 and ipv6. Here use ip().protocol() to judge the protocol type, leaving only the ipv4 type information. Screening information is often needed when we write programs.
Program running effect
Click to get local information, and the network information of this machine (including host name, network card name, ip address, etc.) will be printed out in the text browsing box. This is because the IPv6 information is filtered out. Usually a network card has two ip addresses, one is ipv4 and the other is ipv6. The network card device lo below is a local loopback network card. The other ens33 is the network card of the virtual machine, which is virtualized by VMware. Clicking Clear Text Information will clear the network information in the text browser box.