How to get server IP automatically when client run in TCP?



  • Hi all

    I have a question, i am using TCP to communicate with the server.
    In server i wrote server->listen(QHostAddress::Any, 12000) and on client side clientSocket->connectToHost(server_add, 12000).

    if I provide hard-code as a server_add (like "192.168.0.20") than it works fine but I need to get server IP automatically when client run(server is already running) and than use this IP inside connectToHost.

    How can I do this?

    Note : Server and Client using same network but installed on different-2 system.


  • Qt Champions 2016

    Hi
    the ip of the server is the ip of that pc.

    Often is randomly assigned but you can also make it fixed.

    If on network with DNS server, you can ask by a name to get
    ip for a machine.

    http://doc.qt.io/qt-5/qhostinfo.html#details

    So best way is to give server fix IP or give it fixed name and use name for lookup.

    If you have zero control over the server machine, you might need to enable the server to broadcast a message and the client will listen for it and that way know server.


  • Moderators

    Hi! This problem has been solved many years ago, see: "zero conf" ("Wikipedia).



  • In short:

    • if it's over the internet you either know the ip in advance (either type it in or change the host file of the client machine) or you pay to register your domain name and you can resolve the name via a DNS.
    • If it's over the LAN then you can broadcast via UDP a "Is there any server out there?" message and have the server replay with its IP address

    A workaround of the payment for an internet server (I admit I used it a few times) is to open an account with a free web hosting service (for example https://byet.host/ ) have the server post its ip address on it and have the clients read the posted ip from that site both using a QNetworkAccessManager. the most rudimentary version of this is having two pages one that register the visitor IP in a file and another that displays the contents of that file (this is of course incredibly prone to hacks); a more refined would be authenticate the server so that only legit connections can post their IP, store the IPs in a database and have the client have some power over removing IPs from the list (if a server went down for example). but this is web programming so it's a story for another place


  • Moderators

    @VRonin Sounds like a really dirty hack :D



  • @Wieland That's why I called it a workaround rather than a solution but when the budget is low the struggle gets real :D



  • I think there is many way to do it, but according to me the best way is use QUdpSocket to get Ip of server or other system.

    I did and running successfully an app on it.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.