结合之前在客户端code连接

编程入门 行业动态 更新时间:2024-10-19 12:35:26
本文介绍了结合之前在客户端code连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有多个以太网的I / F。为eth0,eth1的,ETH2 ......我想连接到外部服务器,例如:1.2.3.4:80。

I have multiple ethernet I/Fs. eth0,eth1,eth2... and I want to connect to an external server, eg 1.2.3.4:80.

我的连接是正常的,但在某些特殊情况下我想连接为eth1,而不是eth0的。服务器的code盘我的接口的IP地址。我想,我需要先连接绑定。如果没有绑定(2)服务器总是得到文从eth0的

My connections are OK, but under some special circumstances I want to connect as eth1 and not eth0. the server's code checks the IP address of my interface. I think that I need to bind before connect. Without bind(2) the server always gets packets from eth0

我要寻找code,演示了这种行为。是否有人有一个链接到一个例子吗?

I am looking for code that demonstrates this behavior. Does anybody has a link to an example?

推荐答案

您不需要绑定(2)这一点。

什么你希望做的,是使用不同的网络接口的与你的插座。若要使用系统默认的网络接口,你需要使用 SO_BINDTODEVICE 与的setsockopt 沿套接字选项。要使用该接口,如eth1的例如,应指定为一个字符串 ifr_name 一个 的ifreq 结构这是场传递给的setsockopt 。要做到这一点,你需要包括<网/ if.h中方式> 头

What you're looking to do here is to use a different network interface with your socket. To use a network interface other than the system default, you need to use the SO_BINDTODEVICE socket option along with setsockopt. The interface you want to use, such as "eth1" for example, should be specified as a string in the ifr_name field of a ifreq struct which is to be passed to setsockopt. To do this, you need to include the <net/if.h> header.

基本上,类似如下(未经测试)code:

Basically, something like the following (untested) code:

int set_interface(int socket_fd, const char* interface_name) { ifreq interface; memset(&interface, 0, sizeof(interface)); strncpy(interface.ifr_name, interface_name, IFNAMSIZ); int res = setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, &ifreq, sizeof(ifreq)); return res; }

此外,请确保您检查返回code,万一的setsockopt 失败。

更多推荐

结合之前在客户端code连接

本文发布于:2023-11-25 23:47:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631824.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   code

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!