Important: Please read the Qt Code of Conduct -

Setting UDP output port?

  • New to Qt and enjoying the experience, however....

    I'm having problems with UDP datagrams??? How do I bind to a known outgoing port?

    First I setup a 'discovery receive socket' on port 30303.....

    //setup Discovery UDP socket on port 30303
    discovery_udpSocket = new QUdpSocket(this);
    connect(discovery_udpSocket, SIGNAL(readyRead()),this, SLOT(processPendingDatagrams()));

    Within the event handler for sending datagram I bind socket again

    // Bind udp socket to Artemis discovery port 30303
    discovery_udpSocket = new QUdpSocket(this);
    //discovery_udpSocket->bind(QHostAddress::Broadcast,30303); // I tried this as well

    // Create test data packet
    // QByteArray datagram = "Message number : " + QByteArray::number(messageNo);
    discovery_udpSocket->writeDatagram(, datagram.size(), QHostAddress::Broadcast,30303);


    When I run the application and run WireShark to analyse the datagrams, the outgoing port is being randomly set each time I send a datagram?

    Any help appreciated :)


    [EDIT: code formatting, Volker]

  • Would you mind formatting your code using the proper tags?

  • EDIT:
    deleted content as it was duplicate of the OP
    please use the edit function to reformat the code (I've done that for you, this time)

  • The reason for needing to know the source & destination ports is due to the fact
    I'm using the MicroChip TCP/IP stack were the UDPOpen API Syntax is:

    UDP_SOCKET UDPOpen(UDP_PORT localport, NODE_INFO *remoteNode, TCP_PORT remotePort)


    localPort [in] = Local UDP port number on which data transfer will occure

    remoteNode [in] = Remote host that contains remotePort

    RemoteNode [in] = UDP port number on remote host to transfer the data from.

  • Have a look at "this forum thread":, they discussed the same topic over there.

  • Thanks for the pointer, from this thread it looks like the send port from within Qt is always random, so it looks like I'll have to write a unique handler for the PIC code...


  • Did you read the thread? Just bind the socket before sending. That's it.

  • Yes I have read the thread, I am binding the port before sending (see above), the outgoing port is random.
    It looks like I can call a Berkley API from the PIC, eliminating the need for the Qt send port parameter, I'll experiment tonight.


  • bind binds a name to a socket. You're simply binding the wrong name, QHostAddress::Broadcast not being an address of any local interface (are you checking the return value of bind? It's probably failing with EADDRNOTAVAIL). Get a copy of TCP/IP Illustrated and/or Unix Network Programming for the gory details.

  • OK that explains it! Thank you, I'll grab a copy of TCP/IP Illustrated, as you suggest, for the 'gory' details :)

Log in to reply