Important: Please read the Qt Code of Conduct -

QTcpSocket, how to set local port

  • Hi guys,

    I am working on TCPIP Client side.
    The requirement is to connect to Server port: 8302 … but Client should use port: 8267.
    I am aware that essentially server can establish connection only by listening his 8302 (regardless of client port number)… but in this case they require specific client port number.
    For test purposes I have server application which accepts any client port.

    Please see attached my source code, I am using using Qt 4.6.1.
    I am assuming that setting local port should be done inside tcpclient.cpp, line 43 (slot_connectToServer() function).
    Cannot access function bind or setLocalPort since they are private.

    I am not advanced user, I apologize in advance if question is stupid :/

    Any help is greatly appreciated…
    [](Uploading 100%)

  • Lifetime Qt Champion


    I was not aware you can set the "outgoing" port for a TCP connection. The operating system uses one of the free ports for this purpose.

    Reading it should be possible to do so at least on Linux. I have not searched for other operating systems, and I don't think there is something ready for that in Qt.

    So if you get this to work, you will most likely have to use native API.


  • @Svirac
    Have a read through

    Although the OP experienced some problems, I think that by the end he got it working from Qt?

    From 2008(!),

    This is currently not possible using the Qt API, no.
    What you'd have to do if you really need to do this is to do the local
    binding of a socket descriptor yourself and then set the socket
    descriptor on the QTcpSocket afterwards using the setSocketDescriptor()
    We do plan to introduce this functionality at a later point though.

    Of course, they may have introduced the functionality in the last ten years... ;-)

  • Hi,

    So is it possible to use bind or set local port on some latter Qt versions?

  • @Svirac
    Is this question addressed to me?

    If it looks like further support was never added, I am suggesting those links are still valid and show you how you may achieve it from Qt.

  • OK I will try those links...
    Appreciate your help guys...

    If you find some more info please drop me a note....

Log in to reply