linux 下获取当前网络连接状态的两种方法


  
  
  1. #include <linux/sockios.h>
  2. #include <sys/socket.h>
  3. #include <sys/ioctl.h>
  4. #include <linux/if.h>
  5. #include <string.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <unistd.h>
  9. #define ETHTOOL_GLINK 0x0000000a /* Get link status (ethtool_value) */
  10. typedef enum { IFSTATUS_UP, IFSTATUS_DOWN, IFSTATUS_ERR } interface_status_t;
  11. typedef signed int u32;
  12. /* for passing single values */
  13. struct ethtool_value
  14. {
  15. u32 cmd;
  16. u32 data;
  17. };
  18. interface_status_t interface_detect_beat_ethtool( int fd, char *iface)
  19. {
  20. struct ifreq ifr;
  21. struct ethtool_value edata;
  22. memset(&ifr, 0, sizeof(ifr));
  23. strncpy(ifr.ifr_name, iface, sizeof(ifr.ifr_name) -1);
  24. edata.cmd = ETHTOOL_GLINK;
  25. ifr.ifr_data = ( caddr_t) &edata;
  26. if (ioctl(fd, SIOCETHTOOL, &ifr) == -1)
  27. {
  28. perror( "ETHTOOL_GLINK failed ");
  29. return IFSTATUS_ERR;
  30. }
  31. return edata.data ? IFSTATUS_UP : IFSTATUS_DOWN;
  32. }
  33. int main (int argc, char *argv[])
  34. {
  35. FILE *fp;
  36. interface_status_t status;
  37. char buf[ 512] = { '\0'};
  38. char hw_name[ 10] = { '\0'};
  39. char *token = NULL;
  40. /* 获取网卡名称 */
  41. if ((fp = fopen( "/proc/net/dev", "r")) != NULL)
  42. {
  43. while (fgets(buf, sizeof(buf), fp) != NULL)
  44. {
  45. if( strstr(buf, "eth") != NULL)
  46. {
  47. token = strtok(buf, ":");
  48. while (*token == ' ') ++token;
  49. strncpy(hw_name, token, strlen(token));
  50. }
  51. }
  52. }
  53. fclose(fp);
  54. //方法一:查看一个文件文件,相对来说比较简单
  55. #if 1
  56. char carrier_path[ 512] = { '\0'};
  57. memset(buf, 0, sizeof(buf));
  58. snprintf(carrier_path, sizeof(carrier_path), "/sys/class/net/%s/carrier", hw_name);
  59. if ((fp = fopen(carrier_path, "r")) != NULL)
  60. {
  61. while (fgets(buf, sizeof(buf), fp) != NULL)
  62. {
  63. if (buf[ 0] == '0')
  64. {
  65. status = IFSTATUS_DOWN;
  66. }
  67. else
  68. {
  69. status = IFSTATUS_UP;
  70. }
  71. }
  72. }
  73. else
  74. {
  75. perror( "Open carrier ");
  76. }
  77. fclose(fp);
  78. #endif
  79. //方法二:用函数吧!有点复杂,但是也是一种有效的办法
  80. #if 1
  81. int fd;
  82. if((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
  83. {
  84. perror( "socket ");
  85. exit( 0);
  86. }
  87. status = interface_detect_beat_ethtool(fd, hw_name);
  88. close(fd);
  89. #endif
  90. switch (status)
  91. {
  92. case IFSTATUS_UP:
  93. printf( "%s : link up\n", hw_name);
  94. break;
  95. case IFSTATUS_DOWN:
  96. printf( "%s : link down\n", hw_name);
  97. break;
  98. default:
  99. printf( "Detect Error\n");
  100. break;
  101. }
  102. return 0;
  103. }

            </div>

猜你喜欢

转载自blog.csdn.net/tbadolph/article/details/84697310