Qt学习笔记-服务器端获取UDP封包源IP地址

时间:2024-03-13 15:36:15

目录

 

简介

源码


简介

本篇博文修改于:

 

Qt文档阅读笔记-QUdpSocket基本表述及简单实现

https://blog.csdn.net/qq78442761/article/details/85258574

 

原理请看上面的博文

 

获取源IP地址的原理:

槽函数中进行获取,记住这种逻辑,很重要,因为Socket里面有个函数叫peerAddr这个不会获取任何东西!

关键源码如下:

QHostAddress srcAddress;
        quint16 nSrcPort;
        QByteArray datagram;
        datagram.resize(m_udpSocket->pendingDatagramSize());
        m_udpSocket->readDatagram(datagram.data(), datagram.size(), &srcAddress, &nSrcPort);;

程序运行截图如下:

Qt学习笔记-服务器端获取UDP封包源IP地址

源码

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

QT_BEGIN_NAMESPACE
class QUdpSocket;
QT_END_NAMESPACE

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

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

protected slots:
    void readPendingDatagrams();

private:
    Ui::Widget *ui;
    QUdpSocket *m_udpSocket;
};

#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 <QUdpSocket>
#include <QNetworkDatagram>
#include <QHostAddress>
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("接收端");

    m_udpSocket = new QUdpSocket(this);

    if(!m_udpSocket->bind(7755)){


        qDebug() << "bind failed! The assert will be triggred!";
        Q_ASSERT(!"bind faile!");
    }

    connect(m_udpSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
}

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

void Widget::readPendingDatagrams()
{
    qDebug() << "readPendingDatagrams called!";
    while(m_udpSocket->hasPendingDatagrams()){

        QHostAddress srcAddress;
        quint16 nSrcPort;
        QByteArray datagram;
        datagram.resize(m_udpSocket->pendingDatagramSize());
        m_udpSocket->readDatagram(datagram.data(), datagram.size(), &srcAddress, &nSrcPort);;
        QString firstData = srcAddress.toString() + " " + QString::number(nSrcPort) + " :";
        ui->textEdit->append(firstData + datagram);
    }
}