1

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;
}
DrYJ
  • 93
  • 3
  • 6
  • Code does not compile as is. Missing main(), includes and definition for struct sockaddr_ll. – thuovila Feb 22 '13 at 18:43
  • ive just given this fuction which has the problem, original code contains main() and all the relevant includes. The code compiles perfectly but when i give the interface name as an input then the error message appears "Error getting interface index!" – DrYJ Feb 24 '13 at 09:33

2 Answers2

3

Here is an example:

http://austinmarton.wordpress.com/2011/09/14/sending-raw-ethernet-packets-from-a-specific-interface-in-c-on-linux/

I hope this helps

O.C.
  • 6,711
  • 1
  • 25
  • 26
  • ^ Example helped alot .. ive been able to fix my code using that .. thanks alot OrcunC .. :) – DrYJ Feb 25 '13 at 07:19
0

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.

mortmann
  • 71
  • 3
  • There is almost never a good time to use `strncpy`: https://stackoverflow.com/a/2565831/1495449. Instead use `snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", device);` (assuming C99). – Jetski S-type Sep 10 '20 at 02:30