免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3033 | 回复: 3
打印 上一主题 下一主题

应用程序如何监测网线插入事件 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-12-27 13:38 |只看该作者 |倒序浏览
内核可以通过netlink通知用户层,比如u盘插入等hotplug事件,以下的程序已经实现了该功能。现在我想自动地获取网线插入的事件,而不用一直去查询,不知道该如何处理?我试着改了socket函数的参数,一直没有成功,我觉得原理应该是一样的。等待高手回答。

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <ctype.h>

#include <sys/un.h>

#include <sys/ioctl.h>

#include <sys/socket.h>

#include <linux/types.h>

#include <linux/netlink.h>

#include <errno.h>

  static int

init_hotplug_sock (void)

{



  struct sockaddr_nl snl;



  const int buffersize = 16 * 1024 * 1024;



  int retval;



  memset(&snl, 0x00, sizeof (struct sockaddr_nl));



  snl.nl_family = AF_NETLINK;



  snl.nl_pid = getpid ();



  snl.nl_groups = 1;



  int hotplug_sock = socket (PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);



  if (hotplug_sock == -1)

    {



      printf ("error getting socket: %s", strerror (errno));



      return -1;



    }



  /* set receive buffersize */



  setsockopt (hotplug_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize,

              sizeof (buffersize));



  retval =

    bind (hotplug_sock, (struct sockaddr *) &snl,

          sizeof (struct sockaddr_nl));



  if (retval < 0)

    {



      printf ("bind failed: %s", strerror (errno));



      close (hotplug_sock);



      hotplug_sock = -1;



      return -1;



    }



  return hotplug_sock;



}



#define UEVENT_BUFFER_SIZE      2048



int

main (int argc, char *argv[])

{



  int hotplug_sock = init_hotplug_sock ();







  while (1)



    {



      char buf[UEVENT_BUFFER_SIZE * 2] = { 0 };



      recv (hotplug_sock, &buf, sizeof (buf), 0);



      printf ("(debug)   %s\n", buf);



    }



  return 0;



}

论坛徽章:
0
2 [报告]
发表于 2010-12-27 15:24 |只看该作者
内核 API ,从内核调用用户空间应用程序
不知道行不行,没用过。

论坛徽章:
0
3 [报告]
发表于 2010-12-29 10:32 |只看该作者
使用内核的API不一定能行, 这主要看网卡的driver是否已经提供了相应的API, PC机上的driver一般都比较完善,但若是嵌入式板就不那么统一了。

论坛徽章:
0
4 [报告]
发表于 2010-12-29 10:42 |只看该作者
试了下是可以的,自己写个driver。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP