用c/c++实现linux下检测网络接口状态

要写个检测网络接口链接状态的东西,又不喜欢不断的ping别的地址,也不想调用其他命令行工具来做这个,于是在google了n多内容未果之后,搜刮到个检测工具的源代码

以下代码在fedora 9 / CentOS 5.2下调试通过:)

  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 , char* [])  
  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, "eth0");  
  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;  


转载:http://blog.csdn.net/liangzhao_jay/article/details/51250816



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值