Important: Please read the Qt Code of Conduct -

UDP Unicast

  • Can the QUdpSocket class be set up to natively support UDP Unicast communications? I can't seem to find anything in the documentation...or maybe I just don't know what I'm looking for. An example would be great.


  • Unicast is the default model. You don't need to setup anything.

  • Thanks. Was just confused since the docs say nothing about "unicast".

    So to set up for unicast UDP, for which I can both send and receive over the same socket, does this look right?

    @void MyUnicastUdpServer::initSocket()
    // initialize UDP for unicast to:, port 5678 (bogus IP and port)

     udpSocket = new QUdpSocket(this);
     udpSocket->bind(QHostAddress(, 5678);
     connect(udpSocket, SIGNAL(readyRead()),
             this, SLOT(readPendingDatagrams()));


    void MyUnicastUdpServer::readPendingDatagrams()
    while (udpSocket->hasPendingDatagrams()) {
    QByteArray datagram;
    QHostAddress sender;
    quint16 senderPort;

         udpSocket->readDatagram(, datagram.size(),
                                 &sender, &senderPort);
         // process The Datagram


    void MyUnicastUdpServer::sendDatagram(QByteArray dgram)
    udpSocket->writeDatagram(,dgram.size(), QHostAddress(, 5678 );


  • I never worked with UDP sockets, but it looks quite ok for me with an exception to the sendDatagram() method. The host address and port used there is that of the host you are sending to (the "remote" host); you give the local address and probably send to yourself :-)

Log in to reply