bind before connect at client code

前端 未结 1 1557
天涯浪人
天涯浪人 2020-12-30 10:08

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

1条回答
  •  一向
    一向 (楼主)
    2020-12-30 10:50

    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.

    0 讨论(0)
提交回复
热议问题