Qt文档阅读笔记-QHostInfo官方解析与实例(根据Host获取IP)
生活随笔
收集整理的這篇文章主要介紹了
Qt文档阅读笔记-QHostInfo官方解析与实例(根据Host获取IP)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
官方解析
QHostInfo提供了一個靜態方法獲取主機名;
QHostInfo中有一個查找機制,可以根據IP找主機名,也可能工具主機名找IP,可以通過調用QHostInfo::lookupHost這個靜態函數進行操作,這里要注意這里是異步發送的,后面將會稍微說明下!
如下例子:
// To find the IP address of qt-project.orgQHostInfo::lookupHost("qt-project.org",this, SLOT(printResults(QHostInfo)));// To find the host name for 4.2.2.1QHostInfo::lookupHost("4.2.2.1",this, SLOT(printResults(QHostInfo)));addresses可以得到這個主機的所有IP(比如www.baidu.com在北京,就會有2個IP與之對應)
如果出現錯誤,可以打印錯誤,如下代碼:
QHostInfo info = QHostInfo::fromName("qt-project.org");注意:如果要發送大量的數據,獲取主機名,或IP,調用槽函數的順序將會不同,這個將會在另外一篇博文中給出(獲取局域網中使用了的IP,以及主機名)
?
博主例子
這里只對官方實例進行補充:
程序運行截圖如下:
程序結構如下:
源碼如下:
widget.h
#ifndef WIDGET_H #define WIDGET_H#include <QWidget>QT_BEGIN_NAMESPACE class QHostInfo; QT_END_NAMESPACEnamespace Ui { class Widget; }class Widget : public QWidget {Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();protected slots:void lookUp(const QHostInfo &host);private:Ui::Widget *ui; };#endif // WIDGET_Hmain.cpp
#include "widget.h" #include <QApplication>int main(int argc, char *argv[]) {QApplication a(argc, argv);Widget w;w.show();return a.exec(); }widget.cpp
#include "widget.h" #include "ui_widget.h" #include <QHostInfo>Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget) {ui->setupUi(this);QHostInfo::lookupHost("www.baidu.com", this, SLOT(lookUp(QHostInfo))); }Widget::~Widget() {delete ui; }void Widget::lookUp(const QHostInfo &host) {if(host.error() != QHostInfo::NoError){qDebug() << "Lookup failed: " << host.errorString();return;}const auto addresses = host.addresses();for(const QHostAddress &address : addresses){qDebug() << "address:" << address.toString() << " hostname:" << host.hostName();} }?
程序打包下載:
https://github.com/fengfanchen/Qt/tree/master/QHostInfoLookupDemo
總結
以上是生活随笔為你收集整理的Qt文档阅读笔记-QHostInfo官方解析与实例(根据Host获取IP)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IDEA工作笔记-自动生成POJO或JP
- 下一篇: OllyDbg笔记-寄存器以及各种关键指