用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. }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章