Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind before connect at client code

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

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?

like image 875
cateof Avatar asked Dec 10 '10 00:12

cateof


1 Answers

You don't need bind(2) for this.

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

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

like image 50
Charles Salvia Avatar answered Oct 13 '22 18:10

Charles Salvia