OpenEdv-开源电子网

 找回密码
 立即注册
正点原子全套STM32/Linux/FPGA开发资料,上千讲STM32视频教程免费下载...
查看: 2450|回复: 0

《I.MX6U 嵌入式Qt开发指南》第十一章 网络编程 11.1 获取本机的网络信息

[复制链接]

1070

主题

1081

帖子

2

精华

超级版主

Rank: 8Rank: 8

积分
4443
金钱
4443
注册时间
2019-5-8
在线时间
1199 小时
发表于 2022-8-3 10:11:44 | 显示全部楼层 |阅读模式
本帖最后由 正点原子运营 于 2022-8-10 17:33 编辑

1)实验平台:正点原子阿尔法Linux开发板
2)  章节摘自【正点原子】《I.MX6U 嵌入式Qt开发指南》

3)购买链接:https://detail.tmall.com/item.htm?id=609033604451
4)全套实验源码+手册+视频下载地址:http://www.openedv.com/docs/boards/arm-linux/zdyz-i.mx6ull.html
5)正点原子官方B站:https://space.bilibili.com/394620890
6)正点原子阿尔法Linux交流群:1027879335





第十一章 网络编程

Qt网络模块为我们提供了编写TCP / IP客户端和服务器的类。它提供了较低级别的类,例如代表低级网络概念的QTcpSocket,QTcpServer和QUdpSocket,以及诸如QNetworkRequest,QNetworkReply和QNetworkAccessManager之类的高级类来执行使用通用协议的网络操作。 它还提供了诸如QNetworkConfiguration,QNetworkConfigurationManager和QNetworkSession等类,实现承载管理。
想要在程序中使用Qt网络模块,我们需要在pro项目配置文件里增加下面的一条语句。
  1. QT       += network
复制代码

11.1 获取本机的网络信息
      为什么先写获取本机网络信息的内容呢?在建立网络通信之前我们至少得获取对方的IP地址。在网络应用中,经常需要用到本机的主机名、IP地址、MAC地址等网络信息,通常通在Windows通过调出命令行cmd窗口输入ipconfig或者在Linux系统中使用ifconfig命令就可以查看相关信息了,在这里我们利用Qt做出一个可以查询的界面和功能出来,为了后面的网络编程打下一个简单的基础。
      Qt提供了QHostInfo和QNetworkInterface类可以用于此类信息查询。更多关于QHostInfo和QNetworkInterface的相关函数可以在Qt的帮助文档中找到。下面我们写代码时会使用到相关的函数,有清楚的注释。

11.1.1 应用实例
      本例目的:了解如何通过QHostInfo和QNetworkInterface类获取本地网络所有接口的信息。
      例07_networkhostinfo,获取本机网络接口信息(难度:一般)。项目路径为Qt/2/07_networkhostinfo。本例获取本机的网络接口信息,打印在文本浏览框上,点击按钮可直接获取,为了清楚看见是重新获取的过程,本例点击获取本机信息按钮后延时1s去刷新获取的信息。点击另一个清空文本信息按钮可以清空文本浏览框上的文本内容。
项目文件07_networkhostinfo.pro文件第一行添加的代码部分如下。
  1. 07_ networkhostinfo.pro编程后的代码

  2. 1   QT       += core gui network

  3. 2

  4. 3   greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

  5. 4

  6. 5   CONFIG += c++11

  7. 6

  8. 7   # The following define makes your compiler emit warnings if you use

  9. 8   # any Qt feature that has been marked deprecated (the exact warnings

  10. 9   # depend on your compiler). Please consult the documentation of the

  11. 10  # deprecated API in order to know how to port your code away from it.

  12. 11  DEFINES += QT_DEPRECATED_WARNINGS

  13. 12

  14. 13  # You can also make your code fail to compile if it uses deprecated APIs.

  15. 14  # In order to do so, uncomment the following line.

  16. 15  # You can also select to disable deprecated APIs only up to a certain version of Qt.

  17. 16  #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

  18. 17

  19. 18  SOURCES += \

  20. 19      main.cpp \

  21. 20      mainwindow.cpp

  22. 21

  23. 22  HEADERS += \

  24. 23      mainwindow.h

  25. 24

  26. 25  # Default rules for deployment.

  27. 26  qnx: target.path = /tmp/${TARGET}/bin

  28. 27  else: unix:!android: target.path = /opt/${TARGET}/bin

  29. 28  !isEmpty(target.path): INSTALLS += target
复制代码
在头文件“mainwindow.h”具体代码如下。
  1. mainwindow.h编程后的代码

  2.     /******************************************************************

  3.     Copyright © Deng Zhimao Co., Ltd. 1990-2021. All rights reserved.

  4.     * @projectName   07_networkhostinfo

  5.     * @brief         mainwindow.h

  6.     * [url=home.php?mod=space&uid=90321]@Author[/url]        Deng Zhimao

  7.     * [url=home.php?mod=space&uid=55957]@EMAIL[/url]         1252699831@qq.com

  8.     * [url=home.php?mod=space&uid=28414]@net[/url]            www.openedv.com

  9.     * @date           2021-04-10

  10.     *******************************************************************/

  11. 1   #ifndef MAINWINDOW_H

  12. 2   #define MAINWINDOW_H

  13. 3

  14. 4   #include <QMainWindow>

  15. 5   #include <QPushButton>

  16. 6   #include <QTextBrowser>

  17. 7   #include <QVBoxLayout>

  18. 8   #include <QHBoxLayout>

  19. 9   #include <QTimer>

  20. 10

  21. 11  class MainWindow : public QMainWindow

  22. 12  {

  23. 13      Q_OBJECT

  24. 14

  25. 15  public:

  26. 16      MainWindow(QWidget *parent = nullptr);

  27. 17      ~MainWindow();

  28. 18

  29. 19  private:

  30. 20      /* 点击获取和清空文本按钮 */

  31. 21      QPushButton *pushButton[2];

  32. 22

  33. 23      /* 文本浏览框用于显示本机的信息 */

  34. 24      QTextBrowser *textBrowser;

  35. 25

  36. 26      /* 水平Widget容器和垂直Widget容器*/

  37. 27      QWidget *hWidget;

  38. 28      QWidget *vWidget;

  39. 29

  40. 30      /* 水平布局和垂直布局 */

  41. 31      QHBoxLayout *hBoxLayout;

  42. 32      QVBoxLayout *vBoxLayout;

  43. 33

  44. 34      /* 定时器 */

  45. 35      QTimer *timer;

  46. 36

  47. 37      /* 获取本机的网络的信息,返回类型是QString */

  48. 38      QString getHostInfo();

  49. 39

  50. 40  private slots:

  51. 41      /* 定时器槽函数,点击按钮后定时触发 */

  52. 42      void timerTimeOut();

  53. 43

  54. 44      /* 显示本机信息 */

  55. 45      void showHostInfo();

  56. 46

  57. 47      /* 启动定时器 */

  58. 48      void timerStart();

  59. 49

  60. 50      /* 清空textBrowser的信息 */

  61. 51      void clearHostInfo();

  62. 52  };

  63. 53  #endif // MAINWINDOW_H

  64. 54
复制代码
头文件里主要是声明两个按钮和一个文本浏览框。另外还有一个定时器,声明一些槽函数,比较简单。
在源文件“mainwindow.cpp”具体代码如下。
  1. mainwindow.cpp编程后的代码

  2.     /******************************************************************

  3.     Copyright &#169; Deng Zhimao Co., Ltd. 1990-2021. All rights reserved.

  4.     * @projectName   07_networkhostinfo

  5.     * @brief         mainwindow.cpp

  6.     * @author        Deng Zhimao

  7.     * @email         1252699831@qq.com

  8.     * @net            www.openedv.com

  9.     * @date           2021-04-10

  10.     *******************************************************************/

  11. 1   #include "mainwindow.h"

  12. 2   #include <QNetworkInterface>

  13. 3   #include <QHostInfo>

  14. 4   #include <QThread>

  15. 5   #include <QDebug>

  16. 6

  17. 7   MainWindow::MainWindow(QWidget *parent)

  18. 8       : QMainWindow(parent)

  19. 9   {

  20. 10      /* 设置位置与大小 */

  21. 11      this->setGeometry(0, 0, 800, 480);

  22. 12

  23. 13      /* 点击获取本地信息按钮和清空文本按钮 */

  24. 14      pushButton[0] = new QPushButton();

  25. 15      pushButton[1] = new QPushButton();

  26. 16

  27. 17      pushButton[0]->setText("获取本机信息");

  28. 18      pushButton[1]->setText("清空文本信息");

  29. 19

  30. 20      /* 按钮的大小根据文本自适应,

  31. 21       * 注意setSizePolicy需要在布局中使用 */

  32. 22      pushButton[0]->setSizePolicy(QSizePolicy::Fixed,

  33. 23                                   QSizePolicy::Fixed);

  34. 24      pushButton[1]->setSizePolicy(QSizePolicy::Fixed,

  35. 25                                   QSizePolicy::Fixed);

  36. 26

  37. 27      /* 水平Widget和垂直Widget用于添加布局 */

  38. 28      hWidget = new QWidget();

  39. 29      vWidget = new QWidget();

  40. 30

  41. 31      /* 水平布局和垂直布局 */

  42. 32      hBoxLayout = new QHBoxLayout();

  43. 33      vBoxLayout = new QVBoxLayout();

  44. 34

  45. 35      /* 文本浏览框 */

  46. 36      textBrowser = new QTextBrowser();

  47. 37

  48. 38      /* 添加到水平布局 */

  49. 39      hBoxLayout->addWidget(pushButton[0]);

  50. 40      hBoxLayout->addWidget(pushButton[1]);

  51. 41

  52. 42      /* 将水平布局设置为hWidget的布局 */

  53. 43      hWidget->setLayout(hBoxLayout);

  54. 44

  55. 45      /* 将文本浏览框和hWidget添加到垂直布局 */

  56. 46      vBoxLayout->addWidget(textBrowser);

  57. 47      vBoxLayout->addWidget(hWidget);

  58. 48

  59. 49      /* 将垂直布局设置为vWidget的布局 */

  60. 50      vWidget->setLayout(vBoxLayout);

  61. 51

  62. 52      /* 设置vWidget为中心部件 */

  63. 53      setCentralWidget(vWidget);

  64. 54

  65. 55      /* 定时器初始化 */

  66. 56      timer = new QTimer();

  67. 57

  68. 58      /* 信号槽连接 */

  69. 59      connect(pushButton[0], SIGNAL(clicked()),

  70. 60              this, SLOT(timerStart()));

  71. 61      connect(pushButton[1], SIGNAL(clicked()),

  72. 62              this, SLOT(clearHostInfo()));

  73. 63      connect(timer, SIGNAL(timeout()),

  74. 64              this, SLOT(timerTimeOut()));

  75. 65  }

  76. 66

  77. 67  MainWindow::~MainWindow()

  78. 68  {

  79. 69  }

  80. 70

  81. 71

  82. 72  void MainWindow::timerStart()

  83. 73  {

  84. 74      /* 清空文本 */

  85. 75      textBrowser->clear();

  86. 76

  87. 77      /* 定时1s */

  88. 78      timer->start(1000);

  89. 79  }

  90. 80

  91. 81  void MainWindow::timerTimeOut()

  92. 82  {

  93. 83      /* 显示本机信息 */

  94. 84      showHostInfo();

  95. 85

  96. 86      /* 停止定时器 */

  97. 87      timer->stop();

  98. 88  }

  99. 89

  100. 90  QString MainWindow::getHostInfo()

  101. 91  {

  102. 92      /* 通过QHostInfo的localHostName函数获取主机名称 */

  103. 93      QString str = "主机名称:" + QHostInfo::localHostName() + "\n";

  104. 94

  105. 95      /* 获取所有的网络接口,

  106. 96       * QNetworkInterface类提供主机的IP地址和网络接口的列表 */

  107. 97      QList<QNetworkInterface> list

  108. 98              = QNetworkInterface::allInterfaces();

  109. 99

  110. 100     /* 遍历list */

  111. 101     foreach (QNetworkInterface interface, list) {

  112. 102         str+= "网卡设备:" + interface.name() + "\n";

  113. 103         str+= "MAC地址:" + interface.hardwareAddress() + "\n";

  114. 104

  115. 105         /* QNetworkAddressEntry类存储IP地址子网掩码和广播地址 */

  116. 106         QList<QNetworkAddressEntry> entryList

  117. 107                 = interface.addressEntries();

  118. 108

  119. 109         /* 遍历entryList */

  120. 110         foreach (QNetworkAddressEntry entry, entryList) {

  121. 111             /* 过滤IPv6地址,只留下IPv4 */

  122. 112             if (entry.ip().protocol() ==

  123. 113                     QAbstractSocket::IPv4Protocol) {

  124. 114                 str+= "IP 地址:" + entry.ip().toString() + "\n";

  125. 115                 str+= "子网掩码:" + entry.netmask().toString() + "\n";

  126. 116                 str+= "广播地址:" + entry.broadcast().toString() + "\n\n";

  127. 117             }

  128. 118         }

  129. 119     }

  130. 120

  131. 121     /* 返回网络信息 */

  132. 122     return str;

  133. 123 }

  134. 124

  135. 125 void MainWindow::showHostInfo()

  136. 126 {

  137. 127     /* 获取本机信息后显示到textBrowser */

  138. 128     textBrowser->insertPlainText(getHostInfo());

  139. 129 }

  140. 130

  141. 131 void MainWindow::clearHostInfo()

  142. 132 {

  143. 133     /* 判断textBrowser是否为空,如果不为空则清空文本 */

  144. 134     if (!textBrowser->toPlainText().isEmpty())

  145. 135

  146. 136         /* 清空文本 */

  147. 137         textBrowser->clear();

  148. 138 }
复制代码
       第90~123行,是本例最重要的代码。
       第93行,通过QHostInfo的localHostName函数获取主机名称。
       第97~98行,通过QNetworkInterface::allInterfaces()获取网络接口列表list类存储IP地址子网掩码和广播地址。如果我们用qDebug()函数打印出list,可以发现获取了所有的网络信息。而我们要提取网络里面的网络信息使用QNetworkAddressEntry。
       第106~107行,使用QNetworkAddressEntry从interface接口里使用函数addressEntries(),获取所有的条目。就可以使用QNetworkAddressEntry的对象entry获取IP地址子网掩码和广播地址。
       第110~118行,因为获取的entries在一个QNetworkInterface下可能有两个IP,分别是ipv4和ipv6。这里使用ip().protocol()来判断协议的类型,只留下ipv4类型的信息。筛选信息在我们写程序常常需要的。

11.1.2 程序运行效果
      点击获取本机信息,在文本浏览框内就打印出本机的网络信息(包括了主机名,网卡名,ip地址等)。这里因为过滤掉了IPv6的信息。通常一个网卡有两个ip地址,一个是ipv4,另一个是ipv6的地址。下面的网卡设备lo,是本地回环网卡。另一个ens33是虚拟机的网卡,由VMware虚拟出来的。点击清空文本信息会清空文本浏览框里的网络信息。
image002.jpg


正点原子逻辑分析仪DL16劲爆上市
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则



关闭

原子哥极力推荐上一条 /2 下一条

正点原子公众号

QQ|手机版|OpenEdv-开源电子网 ( 粤ICP备12000418号-1 )

GMT+8, 2024-6-8 16:44

Powered by OpenEdv-开源电子网

© 2001-2030 OpenEdv-开源电子网

快速回复 返回顶部 返回列表