PDA

View Full Version : Use specific port on a client QTcpSocket



TonyInSoMD
8th August 2018, 12:58
I'm trying to set it up so that when a client connects to a server, the client uses a specified port. Right now the client uses a random port. It looked like binding would work, but it didn't change anything it still used a random port. Is there a way to force the client to use a specific port? I'm using Windows 10, Visual Studio 2013, and Qt 5.4.1 64-bit. If you need something like a sample of the code, let me know. It's kind of a pain. My work computer doesn't have internet, so I have to burn it to a CD, carry it over, and transfer to the computer that has internet. But if it will help, I'm willing to do it.

wysota
20th August 2018, 09:09
Why do you need the client to use a specified port? This is not usually desired as the port might be in use by some other software. You should be able to use bind() to do this unless your OS prevents you from binding to a specific port (e.g. ports lower than 1024 are usually reserved).

TonyInSoMD
21st August 2018, 13:04
For whatever reason, IT department asked for it if possible. I used the following code but it doesn't seem to work.



.h
QTcpSocket *m_pSocketClient;

.cpp
m_pSocketClient = new QTcpSocket(this);
m_pSocketClient->bind(Specified Address, Specified Port);
m_pSocketClient->connectToHost(Server Address, Server Port);


It still uses a random port. What am I doing wrong?

wysota
21st August 2018, 21:46
What is the port you're trying to bind to? Does bind() return true? Note, you might need to force a flag for reusing the port, otherwise you won't be able to bind the socket shortly (e.g. minutes) after the previous connection using that port is closed.

TonyInSoMD
22nd August 2018, 22:36
It's returning true. For testing purposes I'm using port 33336. The chances of that one being used are slim. I've tried all the possible flags, and none of them made a difference. It still uses a random port