how to bind raw socket to specific interface

前端 未结 3 1961
离开以前
离开以前 2020-11-29 22:04

My application is running on CentOS 5.5. I\'m using raw socket to send data:

sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (sd < 0) {
  // Error
}
const         


        
3条回答
  •  没有蜡笔的小新
    2020-11-29 22:27

    const char *opt;
    opt = "eth0";
    const len = strnlen(opt, IFNAMSIZ);
    if (len == IFNAMSIZ) {
        fprintf(stderr, "Too long iface name");
        return 1;
    }
    setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, opt, len);
    

    First line: set up your variable

    Second line: tell the program which interface to bind to

    Lines 3-5: get length of interface name and check if it's size not too big.

    Six line: set the socket options for socket sd, binding to the device opt.

    setsockopt prototype:

    int setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen);
    

    Also, make sure you include the if.h, socket.h and string.h header files

提交回复
热议问题