我有多个以太网 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.
更多推荐
在客户端代码连接之前绑定
发布评论