如何选择要使用的网络接口? [英] How to choose which Network interface to use?
问题描述
我使用Qt进行TCP通信.如果我的PC有2个网络接口(例如eth0,eth1),并说我想显式使用eth1,该如何在Qt中做到这一点?
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?
推荐答案
QTcpServer :: listen将要侦听的接口地址作为第一个参数.
QTcpServer::listen takes address of the interface you want to listen as the first argument.
如果您的IP地址在eth0上为192.168.0.1,在eth1上为10.0.0.0.1,那么
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将仅侦听eth0上的端口8080,serv1将仅侦听eth1上的端口8080.
serv0 will listen only port 8080 on eth0 and serv1 will listen only port 8080 on eth1.
由于操作系统根据内核路由表确定QTcpSocket,因此无法指定QTcpSocket应该使用哪个接口.
There is no way to specify which interface should QTcpSocket use since it is decided by operation system according to the kernel routing table.
您可以使用QNetworkInterface :: allAddresses()获取可用的接口地址列表.
You can use QNetworkInterface::allAddresses() to get list of interfaces addresses available.
这篇关于如何选择要使用的网络接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!