Question

Hi i am trying to do packet injection using raw sockets, i have a problem in getting the interface index using SIOCGIFINDEX command of the ioctl. I am using ubuntu 12.04 as my OS. Please help the code is:

int BindRawSocketToInterface(char *device, int rawsock, int protocol)
{
struct sockaddr_ll sll;
struct ifreq ifr;
bzero(&sll, sizeof(sll));
bzero(&ifr, sizeof(ifr));

/* First Get the Interface Index */

strncpy ((char*) ifr.ifr_name, device, IFNAMSIZ);
if ((ioctl(rawsock, SIOCGIFINDEX, &ifr))== -1)
{
printf ("Error getting interface index!\n");
exit(-1);
}

/* Bind our rawsocket to this interface */

sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
sll.sll_protocol = htons(protocol);

if ((bind(rawsock, (struct sockaddr*)&sll,sizeof(sll)))== -1)
{
perror("Error binding raw socket to interface \n");
exit(-1);
}
return 1;
}

OTHER TIPS

As a reminder for anyone searching for such a function, i've seen many variants of this function and many of them have the following bug, so its probably a copy paste bug to be warned of:

strncpy ((char*) ifr.ifr_name, device, IFNAMSIZ);

This line has an OBOE (off-by-one error) and an unnecessary cast to char *.

strncpy (ifr.ifr_name, device, sizeof ifr.ifr_name - 1);

should be used instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top