【问题标题】:error getting interface index using SIOCGIFINDEX使用 SIOCGIFINDEX 获取接口索引时出错
【发布时间】:2013-02-22 18:26:46
【问题描述】:

您好,我正在尝试使用原始套接字进行数据包注入,我在使用 ioctl 的 SIOCGIFINDEX 命令获取接口索引时遇到问题。我使用 ubuntu 12.04 作为我的操作系统。请帮助代码是:

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;
}

【问题讨论】:

  • 代码无法按原样编译。缺少 main()、struct sockaddr_ll 的包含和定义。
  • ive 刚刚给出了这个有问题的功能,原始代码包含 main() 和所有相关的包含。代码编译完美,但是当我将接口名称作为输入时,会出现错误消息“获取接口索引时出错!”

标签: sockets network-programming ubuntu-12.04 ioctl packet-injection


【解决方案1】:

【讨论】:

  • ^ 示例帮助了很多 .. 我能够使用它修复我的代码 .. 非常感谢 OrcunC .. :)
【解决方案2】:

提醒任何搜索此类功能的人,我已经看到此功能的许多变体,其中许多存在以下错误,因此可能是要警告的复制粘贴错误:

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

此行有一个 OBOE(差一错误)和不必要的 char * 强制转换。

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

应该改为使用。

【讨论】:

  • 几乎从来都不是使用strncpy的好时机:stackoverflow.com/a/2565831/1495449。而是使用 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", device);(假设 C99)。
猜你喜欢
  • 1970-01-01
  • 2013-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-21
相关资源
最近更新 更多