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 circumsta
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 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.