Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1120287
  • 博文数量: 177
  • 博客积分: 761
  • 博客等级: 上士
  • 技术积分: 1518
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-04 22:37
文章分类

全部博文(177)

文章存档

2017年(1)

2016年(3)

2015年(33)

2014年(48)

2013年(60)

2012年(32)

分类: 系统运维

2012-11-22 10:56:54

   在某些应用中需要检测到网卡是否处于link状态,来决定如何处理。查看了下网上已有诸多方式可以实现这些功能,通过调用shell执行来查看网卡的状态是否处于RUNNING状态。可是我试了下此方法并不靠谱。
无论我的RJ45处于link up or link down查看到的状态是RUNNING。
eth1      Link encap:Ethernet  HWaddr 00:22:A2:00:10:11
          inet addr:192.168.2.1  Bcast:192.168.2.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1415 errors:0 dropped:0 overruns:0 frame:0
          TX packets:120 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:100515 (98.1 KiB)  TX bytes:9401 (9.1 KiB)
          Interrupt:106
无独有偶在一个网页上找到了用c实现的代码,原作者不详,经验证是可以检测网络的端口状态的。


点击(此处)折叠或打开

  1. #include <sys/types.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <sys/ioctl.h>
  5. #include <stdio.h>
  6. #include <errno.h>
  7. #include <net/if.h>
  8.   
  9. struct ethtool_value {
  10.         __uint32_t cmd;
  11.         __uint32_t data;
  12. };
  13.   
  14. int main(int argc, char* argv[])
  15. {
  16.     struct ethtool_value edata;
  17.     int fd = -1, err = 0;
  18.     struct ifreq ifr;
  19.   
  20.         memset(&ifr, 0, sizeof(ifr));
  21.         strcpy(ifr.ifr_name, "eth1");
  22.         fd = socket(AF_INET, SOCK_DGRAM, 0);
  23.         if (fd < 0) {
  24.                 perror("Cannot get control socket");
  25.                 return 70;
  26.         }
  27.   
  28.         edata.cmd = 0x0000000a;
  29.         ifr.ifr_data = (caddr_t)&edata;
  30.         err = ioctl(fd, 0x8946, &ifr);
  31.         if (err == 0) {
  32.                 fprintf(stdout, "Link detected: %s\n",
  33.                         edata.data ? "yes":"no");
  34.         } else if (errno != EOPNOTSUPP) {
  35.                 perror("Cannot get link status");
  36.         }
  37.    return 0;
  38. }
阅读(6901) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~