Search code examples
c++csocketsraw-sockets

setsockopt() for a raw socket fd failed


Description:

I use:

int syn_socket = (AF_INET, SOCK_RAW, IPPROTO_RAW);

to create a raw socket, I have root privilege. And then:

int on = 1;
int rc = setsockopt(syn_socket, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on));

setsockopt returns -1, and errno is EBADF. And here is the log:

[ 2016-12-05 11:02:34 UTC ] [ syn.cpp:266 ] [ syn ] create raw socket (255)
[ 2016-12-05 11:02:34 UTC ] [ syn.cpp:220 ] [ send_syn_packet ] setsockopt(255) failed. (Ba d file descriptor)
[ 2016-12-05 11:02:34 UTC ] [ syn.cpp:292 ] [ syn ] send syn packet failed.


Solution

  • int syn_socket = (AF_INET, SOCK_RAW, IPPROTO_RAW);
    

    As @DaV already hinted at, this is not calling socket(). The word socket is absent from that line. It compiles, because it is still valid C. If you write:

    int a = (1, 2, 3);
    

    The result is that a is set to the value 3. Your syn_socket is set to IPPROTO_RAW, which is equivalent to 255, which indeed most likely is not a valid descriptor.

    You need to call socket():

    int syn_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);