Hello,

I am programming a generic communication library that can use different layers, such as UDP, TCP and Serial ports.
As I want to be generic, I can use only the functions of QIODevice to write and read from the devices. But I have problems with UDP.

It is written in the doc that QUdpSocket can be used with the standard read and write functions of QIODevice, however I can't get it to work properly. I would like to bind my socket to a local address and port, and to send datagrams to a fixed address and port, but without using the writeDatagram and readDatagram functions (as I need to stay generic).

The doc states that I need to use bind() for the local address and port, and connectToHost() for the remote address and port, but if I do:

Qt Code:
  1. QUdpSocket* socket = new QUdpSocket(this);
  2. if (socket->bind(localAddress, localPort, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint))
  3. {
  4. qDebug() << "UDP Socket:" << socket->peerAddress() << socket->peerPort() << socket->localAddress() << socket->localPort();
  5. socket->connectToHost(hostAddress, hostPort);
  6. qDebug() << "UDP Socket:" << socket->peerAddress() << socket->peerPort() << socket->localAddress() << socket->localPort();
  7. return socket;
  8. }
To copy to clipboard, switch view to plain text mode 

I get the following output:
UDP Socket: QHostAddress( "" ) 0 QHostAddress( "192.168.9.44" ) 8882
UDP Socket: QHostAddress( "192.168.9.33" ) 8881 QHostAddress( "192.168.9.33" ) 56859
The bind() works and bind the local address (44) and port (8882), but the peer address is still null (that's normal), and then when I call connectToHost(), the peer address is fine but the local address gets overwritten. Is this a bug in Qt ?

And if I call them in the reverse order, I get an error:
UDP Socket: QHostAddress( "192.168.9.33" ) 8881 QHostAddress( "192.168.9.33" ) 62557
QNativeSocketEngine::bind() was not called in QAbstractSocket::UnconnectedState
Does anyone know how to use the QUdpSocket with read and write only, and with the local address and port specified ?

Thank you,
Alexandre