Paul Grinberg
Paul Grinberg

Reputation: 1407

Platform independent Qt5 way to get open TCP port

Is there a platform independent way in Qt to get an unused TCP port? I have a need to launch an existing application which must be given an open TCP port in order for it to work.

Upvotes: 6

Views: 2405

Answers (2)

0xFFFFFFFF
0xFFFFFFFF

Reputation: 852

use QTcpServer is easier way.

bool QTcpServer::listen(const QHostAddress & address = QHostAddress::Any, quint16 port = 0)

If port is 0, a port is chosen automatically, then you use quint16 QTcpServer::serverPort() const to get the "idle" port

then close your Tcp Server

OR

generate a ramdom port, use QTcpSocket to connect it(local connection)

  1. if connected, your port is QTcpSocket::localPort() and close this tcp socket
  2. if not connected, your port is random port;

Upvotes: 7

Evgeny
Evgeny

Reputation: 4010

Do you mean some kind of tcp server? Then there is QTcpServer class.

If you want to start an existiong server, then you need QProcess class. Example:

QString program = "path/to/server";
QStringList arguments;
arguments << "-p" << "1234"; //or what ever you want

QProcess *myProcess = new QProcess(parent);
myProcess->start(program, arguments);

Upvotes: 0

Related Questions