bind socket to network interface

前端 未结 3 764
天涯浪人
天涯浪人 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:28

    Maybe someone will find it useful, so I am sharing the solution that worked for me (Linux, C++):

    uint32_t interfaceIndex = if_nametoindex(interfaceName);
    

    Where "interfaceName" is the name of the interface we want to bind to, e.g. "eth0" (see: https://linux.die.net/man/3/if_nametoindex). Now we can specify this interface in the socket address structure via "sin6_scope_id" (in case we use IPv6):

    struct sockaddr_in6 socketAddress;
    socketAddress.sin6_scope_id = interfaceIndex;
    

    Now we can bind the socket to the interface via "bind" as usual.

提交回复
热议问题