bind socket to network interface

前端 未结 3 738
天涯浪人
天涯浪人 2020-12-02 17:49

How can I bind a socket to a particular network interface? I tried using setsockopt on server side, but the clients can still access the service through both et

3条回答
  •  温柔的废话
    2020-12-02 18:04

    You can bind to a specific interface by setting SO_BINDTODEVICE socket option.

    struct ifreq ifr;
    
    memset(&ifr, 0, sizeof(ifr));
    snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "eth0");
    if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) {
        ... error handling ...
    }
    

    Warning: You have to be root and have the CAP_NET_RAW capability in order to use this option.

    The second method is that you can resolv IP address tied to an interface with getifaddrs().

    Follow the latter link for a comprehensive example.

提交回复
热议问题