Qt4 DNS Proxy QUdpSocket

2019-05-23 23:30发布

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);
}

标签: c++ qt proxy qt4 dns
1条回答
爷、活的狠高调
2楼-- · 2019-05-23 23:57

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);
查看更多
登录 后发表回答