views:

140

answers:

3

I use Qt for my TCP communication. If my PC has 2 network interfaces (say eth0, eth1), and say I want to explicitly use eth1, how do I do that in Qt?

+1  A: 

That's not a Qt question, that's a socket question. Bind() to the address on eth1. You have to hope that the routing table will actually do what you expect when you do that.

Andrew McGregor
+2  A: 

It doesn't look like Qt's network API supports binding to interfaces for TCP connections. There is a QUdpSocket::bind function, but apparently no corresponding function for QTcpSocket objects.

If Qt doesn't give you the control you need, you may need to drop down to the OS level socket functions instead. Fortunately, the Berkeley Socket API is mostly cross-platform with only minor differences between operating systems.

Greg Hewgill
+2  A: 

QTcpServer::listen takes address of the interface you want to listen as the first argument.

If you have IP address 192.168.0.1 on eth0 and 10.0.0.0.1 on eth1 then

QTcpServer serv0;
QTcpServer serv1;

serv0.listen( QHostAddress("192.168.0.1"), 8080 );
serv1.listen( QHostAddress("10.0.0.0.1"), 8080 );

serv0 will listen only port 8080 on eth0 and serv1 will listen only port 8080 on eth1.

There is no way to specify which interface should QTcpSocket use since it is decided by operation system according to the kernel routing table.

You can use QNetworkInterface::allAddresses() to get list of interfaces addresses available.

VestniK