1

I'm testing a P2P communication by udp with Qt 5.4(on Windows 10 64bit).

On Windows to Windows, this code can get a message("SendFromHost") from an another device. But on Android to Windows, this code got a own sent message("SendFromGuest") and finished the program.

Please tell me how to get a message without own sent.

void Network::start()
{
    findLanSocket = new QUdpSocket(this);
    connect(findLanSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
                this, SLOT(onUdpStateChanged(QAbstractSocket::SocketState)));
    findLanSocket->bind(findPort, QUdpSocket::ShareAddress);

    QByteArray datagram = "SendFromGuest";
    findLanSocket->writeDatagram(datagram.data(), datagram.size(), QHostAddress::Broadcast, findPort);
}

void Network::onUdpStateChanged(QAbstractSocket::SocketState s)
{
    if (s == QAbstractSocket::BoundState) {
        connect(findLanSocket, SIGNAL(readyRead()), this, SLOT(onReadyUdpRead()));
    }
}

void Network::onReadyUdpRead()
{
    QByteArray datagram; QHostAddress haddr;
    datagram.resize(findLanSocket->pendingDatagramSize());
    findLanSocket->readDatagram(datagram.data(), datagram.size(), &haddr);

    QString rev = QString::fromUtf8(datagram);
    if (rev == "SendFromHost"){
        result = haddr.toString();
        qDebug() << result;
        success();
        return;
    }
}
Tank2005
  • 899
  • 1
  • 14
  • 32

1 Answers1

0

A broadcast UDP datagram can also be received by its sender, that's the expected behavior. See How to ignore your own broadcast udp packets for instance.

Community
  • 1
  • 1
Ilya
  • 5,377
  • 2
  • 18
  • 33
  • Do you know the option parameters for Qt 5? – Tank2005 Jan 15 '16 at 12:06
  • I don't think Qt provides an option for that (apart from doing multicast instead of broadcast). For broadcast, you'd have to use one of the trick in the answers I've linked to. – Ilya Jan 15 '16 at 17:36
  • Note: for me, I'd not use the IP address but insert a unique (internally-generated) ID in the datagram, so that I'm able to identify my own messages (because they contain my ID) and discard them. – Ilya Jan 15 '16 at 17:44