QT开发之IP协议

IP协议就不讲了,以前在Linux网络编程这一块讲的非常清楚了,这篇文章只是一个演示怎么在QT中去使用库函数来运用IP相关的操作.


新建Qt  Gui应用项目,名称为myIP,其他类保持默认,在工程文件中添加QT  += network


mian.cpp

#include <QtGui/QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    
    return a.exec();
}

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class QHostInfo;

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
    
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    
private:
    Ui::MainWindow *ui;

private slots:
    void lookedUp(const QHostInfo &host);
};

#endif // MAINWINDOW_H

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtNetwork>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
#if 0
    QString localHostName = QHostInfo::localHostName();
    QHostInfo info = QHostInfo::fromName(localHostName);
    qDebug() << "localHostName = " << localHostName << endl
             << "IP:" << info.addresses();
#else
    QList<QNetworkInterface> list=QNetworkInterface::allInterfaces();
    foreach(QNetworkInterface interface,list)
    {
        qDebug() << "Name:" << interface.name();
        qDebug() << "HardwareAddress:" << interface.hardwareAddress();

        QList<QNetworkAddressEntry> entryList = interface.addressEntries();
        foreach(QNetworkAddressEntry entry ,entryList)
        {
            qDebug() << "IP Address:" << entry.ip().toString();
            qDebug() << "NetMask:" << entry.netmask().toString();
            qDebug() << "Broadcast:" << entry.broadcast().toString();
        }

    }
#endif

    QHostInfo::lookupHost("www.baidu.com",this,SLOT(lookedUp(QHostInfo)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::lookedUp(const QHostInfo &host)
{
    if(host.error()!=QHostInfo::NoError)
    {
        qDebug() << "Lookup failed:" << host.errorString();
        return;
    }
    foreach(QHostAddress address,host.addresses())
    {
        if(address.protocol()==QAbstractSocket::IPv4Protocol)
            qDebug() <<  "Found address:" << address.toString();
    }
}


已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页