如何使用 Qt 獲得主機IP地址及接口 詳細介紹
如何使用 Qt 獲得主機IP地址及接口是本文介紹的內容,不多說,先來看內容。QNetworkInterface類提供了一個主機IP地址和網絡接口的列表。
QNetworkInterface提供了一個依附于主機的網絡接口,程序可以在上面運行。每個網絡接口包括0~n個IP地址,每個都可選的配有網絡掩碼或廣播地址。
前提條件---下載安裝***版的Qt for Symbian - Installation packages
傳統函數返回host機器上所有的ip地址
- QNetworkInterface *inter=new QNetWorkInterface();
- inter->allAddresses();
返回host機器上發現的所有網絡接口的列表
- QNetworkInterface *inter=new QNetWorkInterface();
- inter->allInterfaces();
頭文件 #ifndef NET_H
- #define NET_H
- #include <QtGui/QWidget>
- #include<QNetworkInterface>
- #include<QList>
- #include<QLabel>
- #include<QHBoxLayout>
- #include<QString>
- #include<QHostAddress>
- #include<QListWidget>
- namespace Ui
- {
- class netClass;
- }
- class net : public QWidget
- {
- Q_OBJECT
- public:
- net(QWidget *parent = 0);
- ~net();
- private:
- QNetworkInterface *inter;
- QLabel *lbl;
- QHBoxLayout *lay;
- QListWidget *item;
- };
- #endif // NET_H
源文件 #include "net.h"
- #include "ui_net.h"
- net::net(QWidget *parent)
- : QWidget(parent)
- {
- QList<QHostAddress> list;
- lbl=new QLabel(this);
- lay=new QHBoxLayout(this);
- item=new QListWidget(this);
- inter=new QNetworkInterface();
- list=inter->allAddresses();
- QString str;
- for (int i = 0; i < list.size(); ++i) {
- str = list.at(i).toString();
- item->addItem(str);
- }
- lay->addWidget(item);
- setLayout(lay);
- }
- net::~net()
- {
- // No need to delete any object that got a parent that is properly deleted.
- delete inter;
- }
獲得網絡接口的代碼 #include "net.h"
- #include "ui_net.h"
- net::net(QWidget *parent)
- : QWidget(parent)
- {
- QList<QNetworkInterface> list;
- lbl=new QLabel(this);
- lay=new QHBoxLayout(this);
- item=new QListWidget(this);
- inter=new QNetworkInterface();
- list=inter->allInterfaces();
- QString str;
- for (int i = 0; i < list.size(); ++i) {
- str = list.at(i).name();
- item->addItem(str);
- }
- lay->addWidget(item);
- setLayout(lay);
- }
- net::~net()
- {
- delete inter;
- }
顯示host IP
顯示網絡接口
小結:如何使用 Qt 獲得主機IP地址及接口 詳細介紹到這里就介紹完了,希望本文對你有所幫助!關于網絡的更多內容,請參考編輯推薦。