Reputation: 21
I am receiving a datagram twice on my QUdpSocket even though I am watching on wireshark and it is only received once. I create the socket and listen on port 11112. There is another device that emits data on this port which I am listening for. I consistently get two messages for each actual message sent. Im not sure what is causing this. Any thoughts?
Stripped down code :
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_socket = new QUdpSocket(this);
connect (m_socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(onSocketStateChange(QAbstractSocket::SocketState)));
m_socket->bind(11112, QUdpSocket::ShareAddress);
}
MainWindow::~MainWindow()
{
delete ui;
delete m_socket;
}
void MainWindow::readPendingDatagrams()
{
QByteArray buffer;
QHostAddress sender;
quint16 port;
while(m_socket->hasPendingDatagrams())
{
int s = m_socket->pendingDatagramSize();
buffer.resize(s);
//for some reason there are two datagrams on the line.
// I have verified with wireshark that there is only one from the
// sender so not sure what is happening under the hood...
m_socket->readDatagram(buffer.data(),buffer.size(),&sender, &port);
QString source = sender.toString().split(":")[3];
if (source == "172.20.23.86")
{
qInfo() << buffer <<endl;
}
}
}
void MainWindow::onSocketStateChange(QAbstractSocket::SocketState state)
{
if ( state == QAbstractSocket::BoundState ) {
connect(m_socket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
}
}
Upvotes: 0
Views: 702
Reputation: 21
Unslander Monica is correct, it binds to all interfaces default, you can fix it by m_socket->bind(QHostAddress::LocalHost,11112);
Upvotes: 0
Reputation: 98425
This may happen if the datagram is sent to a broadcast address, and you’re bound to all interfaces (0.0.0.0), and there are two interfaces the datagram is received on. To exclude this possibility, switch to the receiveDatagram
API and dump the full details of the datagram you’ve received. My bet is that the interfaces you receive it on will be different each time.
You're also connecting the readPendingDatagrams
slot potentially multiple times, and it may thus be fired multiple times, although hasPendingDatagrams
should return false
the second time round - so while this may be not be the problem, it is a problem that you must fix. It should only be connected once - when you construct the socket, i.e. in the constructor.
Upvotes: 2