Qt UDP Socket – specify source port

Have you ever had to use a QUdpSocket to send data from a specific port?  I had to do this earlier, and I figured out how to do it(although not using Qt-only APIs).

My problem was as follows: I need to be able to receive on a specific port.  The device that I am talking to listens on this port and then responds back on that same port, no matter what my source port is.  So to keep things clean, I figured that it would be best to use just one single socket to send and receive data packets.

The general consensus that I saw after searching Google was that it is not possible to do this.  It is possible, but it doesn’t seem possible using Qt-only APIs.  I knew that it was possible, as I have done this before.  This is the code that I came up with:

 

    int optval = 1;
    int fd;
    struct sockaddr_in socket_config;

    memset( &socket_config, 0, sizeof( struct sockaddr_in ) );

    fd = socket( AF_INET, SOCK_DGRAM, 0 );
    if( fd < 0 ){
        // error handling goes here
    }

    socket_config.sin_port = htons( port );
    if( bind( fd, (struct sockaddr*)&socket_config, sizeof( struct sockaddr_in ) ) < 0 ){
        // error handling goes here
    }

    if( setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof( optval ) ) < 0 ){ // error handling goes here } 

    udp_socket = new QUdpSocket(); 
    udp_socket->setSocketDescriptor( fd );


This allows us to still re-use the proper port, but use the socket in a Qt-like way.

Leave a Reply

Your email address will not be published. Required fields are marked *