如何选择使用哪个网络接口? [英] How to choose which Network interface to use?

查看:16
本文介绍了如何选择使用哪个网络接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 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.

如果您在 eth0 上有 IP 地址 192.168.0.1,在 eth1 上有 10.0.0.1,那么

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

QTcpServer serv0;
QTcpServer serv1;

serv0.listen( QHostAddress("192.168.0.1"), 8080 );
serv1.listen( QHostAddress("10.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应该使用哪个接口,因为它是由操作系统根据内核路由表决定的.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆