Qt文档阅读笔记-QHostInfo官方解析与实例(根据Host获取IP)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq78442761/article/details/89310690

官方解析

QHostInfo提供了一个静态方法获取主机名;

QHostInfo中有一个查找机制,可以根据IP找主机名,也可能工具主机名找IP,可以通过调用QHostInfo::lookupHost这个静态函数进行操作,这里要注意这里是异步发送的,后面将会稍微说明下!

如下例子:

  // To find the IP address of qt-project.org
  QHostInfo::lookupHost("qt-project.org",
                        this, SLOT(printResults(QHostInfo)));

  // To find the host name for 4.2.2.1
  QHostInfo::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_NAMESPACE

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

protected slots:
    void lookUp(const QHostInfo &host);

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

main.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

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/89310690
今日推荐