Qt4 DNS Proxy QUdpSocket

扶醉桌前 提交于 2020-01-02 15:02:35

问题


I'm essentially trying to make a DNS proxy application using Qt4. If I set my DNS nameserver to 'localhost' then I want to forward all DNS requests to the server specified in the remoteSocket object. Everything seems to be working fine except sending the data from the remoteSocket object back to the localSocket object which is requesting the DNS lookup.

When writing to localSocket, is there anything specific I need to know about that? The problem seems to be in readResponse().

#include "dns.h"

Dns::Dns()
{
}

void Dns::initSocket()
{
    localDatagram = new QByteArray();
    remoteDatagram = new QByteArray();

    localSocket = new QUdpSocket();
    connect(localSocket, SIGNAL(readyRead()), this, SLOT(readRequest()), Qt::DirectConnection);
    localSocket->bind(QHostAddress::LocalHost, 53);

    remoteSocket = new QUdpSocket();
    remoteSocket->connectToHost(QHostAddress("4.2.2.1"), 53);
    connect(remoteSocket, SIGNAL(readyRead()), this, SLOT(readResponse()), Qt::DirectConnection);

}

void Dns::readRequest()
{
    while (localSocket->hasPendingDatagrams()) {
        localDatagram->resize(localSocket->pendingDatagramSize());\
        localSocket->readDatagram(localDatagram->data(), localDatagram->size());
        remoteSocket->write(*localDatagram);
    }
}

void Dns::readResponse()
{
    QByteArray bytes(remoteSocket->readAll());
    qDebug() << "BYTES: [" << bytes.toBase64() << "]";
    localSocket->write(bytes);
}

回答1:


I was assuming that using QUdpSocket::bind(), the resulting socket object would be able to obtain the peerAddress/peerPort using the access methods, however that was not the case.

The final solution was to do:

QHostAddress sender;
quint16 senderPort;

localSocket->readDatagram(localDatagram->data(), localDatagram->size(), &sender, &senderPort);

And in readResponse(),

localSocket->writeDatagram(bytes, sender, senderPort);


来源:https://stackoverflow.com/questions/1392494/qt4-dns-proxy-qudpsocket

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!