Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QT Trying to receive data from specific IP address using UDP



  • I am trying to receive data from specific IP address (like 166.0.0.245) using UDP protocol in QT. I am having multiple connections in my network which are udp. But the problem is i am receiving from any ip address rather than specific IP address.

    Below i am attaching my code where i am setting the ip address of my receiver i.e 166.0.0.34 and my senders IP address is 166.0.0.245 -> where do i specifically set this ip address so that i can receive only that ip address and discard rest of the ip address in my network. Plz can somebody suggest me where do i specifically set my ip address at the receivers side which accepts only one sender with specific ip address and port.

    Thanks in advance

    NetBroadcasterDlg::NetBroadcasterDlg(QWidget *parent) : //Main Function QWidget(parent), ui(new Ui::NetBroadcasterDlg) {

    //ethernet initialisation and binding wini
    udpSocket = new QUdpSocket(this);
    udpSocket_send = new QUdpSocket(this);

    udpSocket->bind(QHostAddress("166.0.0.34"), 1100, QUdpSocket::ShareAddress);
    connect(udpSocket, SIGNAL(readyRead()),
    this, SLOT(processPendingDatagrams()));
    ... }

    void NetBroadcasterDlg::processPendingDatagrams() {

    //Read data from ethernet
    while (udpSocket->hasPendingDatagrams()) {
    datagram.resize(int(udpSocket->pendingDatagramSize()));

    udpSocket->readDatagram(datagram.data(), datagram.size()); 
    

    // Sending data to the Target

    udpSocket_send->writeDatagram(datagram.data(), datagram.size(),
                             QHostAddress("166.168.1.20"), 2500);   //target address and port
    

    ... }


  • Lifetime Qt Champion

    @inzamam said in QT Trying to receive data from specific IP address using UDP:

    receiving from any ip address rather than specific IP address.

    If more processes sending to your QUdpServer to the correct port you have to use QUdpSocket::readDatagram() and inspect the sender address.



  • @Christian-Ehrlicher Thanks, i have inspected it , but how do i specifically set @ receivers end take only this ip address and rest all neglect it.


  • Lifetime Qt Champion

    @inzamam said in QT Trying to receive data from specific IP address using UDP:

    but how do i specifically set @ receivers end take only this ip address and rest all neglect it.

    Take a look at the functions of QNetworkDatagram and you will find a lot of stuff - even a function to get the sender address.



  • @Christian-Ehrlicher Thanks i'll look into that.



  • Thanks, I got it while i tried using the below code.

    QHostAddress fromAddress;
    udpSocket->readDatagram(datagram.data(), datagram.size(),&fromAddress);

    if(fromAddress.isEqual(QHostAddress("166.0.0.245"))
    {
    // filtered data
    }


Log in to reply