在客户端代码连接之前绑定

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

我有多个以太网 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.服务器的代码检查我的接口的 IP 地址.我认为我需要在连接之前绑定.如果没有 bind(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

我正在寻找演示此行为的代码.有人有示例的链接吗?

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

推荐答案

你不需要 bind(2) .

您在这里要做的是使用与您的套接字不同的网络接口.要使用系统默认以外的网络接口,您需要使用 SO_BINDTODEVICE 套接字选项和 setsockopt.您要使用的接口,例如 "eth1",应在 ifr_name 字段中指定为字符串linux.about/library/cmd/blcmdl7_netdevice.htm" rel="noreferrer">ifreq struct 将被传递给 setsockopt.为此,您需要包含 <net/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.

基本上,类似于以下(未经测试的)代码:

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; }

另外,请务必检查返回码,以防 setsockopt 失败.

Also, make sure you check the return code, in case setsockopt fails.

更多推荐

在客户端代码连接之前绑定

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

发布评论

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

>www.elefans.com

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