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

要写个检测网络接口链接状态的东西,又不喜欢不断的ping别的地址,也不想调用其他命令行工具来做这个,于是在google了n多内容未果之后,搜刮到个检测工具的源代码,从里面抠出来一块儿就ok了,版权不是我的哦,哈哈……

以下代码在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. struct ethtool_value {
  9.         __uint32_t      cmd;
  10.         __uint32_t      data;
  11. };
  12. int main(int , char* [])
  13. {
  14.     struct ethtool_value edata;
  15.     int fd = -1, err = 0;
  16.     struct ifreq ifr;
  17.         memset(&ifr, 0, sizeof(ifr));
  18.         strcpy(ifr.ifr_name, "eth0");
  19.         fd = socket(AF_INET, SOCK_DGRAM, 0);
  20.         if (fd < 0) {
  21.                 perror("Cannot get control socket");
  22.                 return 70;
  23.         }
  24.         edata.cmd = 0x0000000a;
  25.         ifr.ifr_data = (caddr_t)&edata;
  26.         err = ioctl(fd, 0x8946, &ifr);
  27.         if (err == 0) {
  28.                 fprintf(stdout, "Link detected: %s/n",
  29.                         edata.data ? "yes":"no");
  30.         } else if (errno != EOPNOTSUPP) {
  31.                 perror("Cannot get link status");
  32.         }
  33.    return 0;
  34. }
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值