问题
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