Reputation: 613
Currently our tool uses QTCPSocket->ConnectToHost
to connect to our TCP server, which works.
The problem arises when some of our machines are bridging two networks, across two entirely different IP ranges (10.x.x.x, 172.x.x.x). When you try to connect to a device on the 172.x.x.x network, it appears to be trying to connect via the 10.x network interface, and then times out and fails to connect. On windows, if you disable the network port for the 10.x network and reload the tool, it correctly uses the 172.x network interface and connects. I can see no way with QTCPSocket to force it to connect using a specific interface, or am I missing something? It seems like the 10.x network is getting priority somehow and we always try to use that when trying to establish an outgoing connection, which is not what we want.
Ideally, the user would be able to select what network interface they want to use to make the connection, whether its the 10.x or 172.x network.
This is using QT 5.15.0.
Upvotes: 1
Views: 1632
Reputation: 2426
You can select the outgoing interface to use by calling bind()
with your interfaces address first. This will select your outgoing address to use.
See the documentation for the bind function:
For TCP sockets, this function may be used to specify which interface to use for an outgoing connection, which is useful in case of multiple network interfaces.
I threw together a very simple demo for you:
Its all running locally. This is the servers main.cpp:
#include <QCoreApplication>
#include <QTcpServer>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTcpServer serv;
QObject::connect(&serv, &QTcpServer::newConnection, [](){
qDebug() << "New connection!";
});
qDebug() << serv.listen(QHostAddress("192.168.x.y"), 1337);
return a.exec();
}
And this is the clients main.cpp:
#include <QCoreApplication>
#include <QDebug>
#include <QTcpSocket>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTcpSocket s;
qDebug() << s.bind(QHostAddress("127.0.0.1"));
s.connectToHost(QHostAddress("192.168.x.y"), 1337);
return a.exec();
}
By calling bind
we tell the client to send packets using the local interface, but as the server only listens to my wifi interface 192.168.x.y the connection will fail. If you now change the following line:
qDebug() << s.bind(QHostAddress("127.0.0.1"));
as such:
qDebug() << s.bind(QHostAddress("192.168.x.y"));
You will see that the server will recieve the connection, as we explicitly selected this interface to send from.
However, the operating system should select the correct interface for you (meaning in the demo: by not calling bind you should get a connection). If that does not happen you have a different issue.
To get a list of all available interfaces you can use QNetworkInterface::allInterfaces()
which will grant you access to everything might you need to know.
Upvotes: 4