结合之前在客户端code连接 [英] bind before connect at client code

查看:97
本文介绍了结合之前在客户端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连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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