Search code examples
c++socketswifiwireless

Why does binding socket to interface fail?


I'm trying to open a raw socket and bind my wireless interface to it. This is the code I am using:

//opening socket
if ((sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1){
    //if socket fails give error
    perror("socket");
}

//binding socket to interface
if (setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, "wlp0s19f2u3", 4) < 0)
    perror("SIOCGIFHWBIND");

But when compiling and running with sudo I get a "SIOCGIFHWBIND: No such device".
I first thought this is because there I miss spelled the interface name but my iwconfig output is:

wlp0s19f2u3  IEEE 802.11  Mode:Monitor  Frequency:2.462 GHz  Tx-Power=20 dBm 

and it isn't an issue with monitor mode because running the code while my wireless card is in managed mode gives the same output and I need the interface to be in monitor mode.
Please help and have a nice day!


Solution

  • Thanks Mark Setchell, turns out the 4 was from example code where they used something like "eth0" which has 4 chars. So replacing 4 with a strlen() of your interface works great. Thanks once again.