嵌入式 hi3518平台检测网线是否插上

时间:2023-03-09 13:04:00
嵌入式 hi3518平台检测网线是否插上
  1. /********************************** (C) COPYRIGHT *******************************
  2. * File Name          : linkstatus_check.c
  3. * Author             : skdkjzz
  4. * Date               : 2014/08/07
  5. * Description        : 网线是否插上
  6. *********************************************************************************/
  7. #include <sys/types.h>
  8. #include <string.h>
  9. #include <stdlib.h>
  10. #include <sys/types.h>
  11. #include <sys/ioctl.h>
  12. #include <sys/stat.h>
  13. #include <stdio.h>
  14. #include <string.h>
  15. #include <errno.h>
  16. #include <net/if.h>
  17. #include <sys/utsname.h>
  18. #include <limits.h>
  19. #include <ctype.h>
  20. #include <sys/socket.h>
  21. #include <netinet/in.h>
  22. #include <arpa/inet.h>
  23. #include <linux/sockios.h>
  24. #define ETHTOOL_GLINK   0x0000000a   /* Get link status (ethtool_value) */
  25. struct ethtool_value {
  26. unsigned int   cmd;
  27. unsigned int   data;
  28. };
  29. int get_netlink_status(const char *if_name);
  30. /****************************************************************
  31. return value:
  32. -1 -- error , details can check errno
  33. 1  -- interface link up
  34. 0  -- interface link down.
  35. ****************************************************************/
  36. int get_netlink_status(const char *if_name)
  37. {
  38. int skfd;
  39. struct ifreq ifr;
  40. struct ethtool_value edata;
  41. edata.cmd = ETHTOOL_GLINK;
  42. edata.data = 0;
  43. memset(&ifr, 0, sizeof(ifr));
  44. strncpy(ifr.ifr_name, if_name, sizeof(ifr.ifr_name) - 1);
  45. ifr.ifr_data = (char *)&edata;
  46. if ((skfd = socket(AF_INET, SOCK_DGRAM, 0)) == 0)
  47. return -1;
  48. if (ioctl(skfd, SIOCETHTOOL, &ifr) == -1)
  49. {
  50. close(skfd);
  51. return -1;
  52. }
  53. close(skfd);
  54. return edata.data;
  55. }
  56. int main()
  57. {
  58. char net_buf[10]="eth0";
  59. printf("Net link status: %s\n", get_netlink_status(net_buf) == 1 ? "up" : "down");
  60. return 0;
  61. }
  62. </span>