Qt4 DNS Proxy QUdpSocket

I am trying to make a DNS proxy application using Qt4. If I set my DNS nameserver to "localhost" then I want to redirect all DNS requests to the server specified in the remoteSocket object. Everything seems to work fine, except for sending data from the remoteSocket object back to the localSocket object, which requests a DNS lookup.

When writing in localSocket, is there anything specific I need to know about this? 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);
}

      

+2


source to share


1 answer


I assumed that with QUdpSocket :: bind () the resulting socket object would be able to get the peerAddress / peerPort using accessor methods, however this is not the case.

The final decision was to do:

QHostAddress sender;
quint16 senderPort;

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

      



And in readResponse (),

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

      

+1


source







All Articles