Linux下C语言获取本机IP地址

  1. #include <sys/ioctl.h>

  2. #include <net/if.h>

  3. #include <arpa/inet.h>

  4.  
  5. char* GetLocalIp()

  6. {

  7. int MAXINTERFACES=16;

  8. char *ip = NULL;

  9. int fd, intrface, retn = 0;

  10. struct ifreq buf[MAXINTERFACES];

  11. struct ifconf ifc;

  12.  
  13. if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0)

  14. {

  15. ifc.ifc_len = sizeof(buf);

  16. ifc.ifc_buf = (caddr_t)buf;

  17. if (!ioctl(fd, SIOCGIFCONF, (char *)&ifc))

  18. {

  19. intrface = ifc.ifc_len / sizeof(struct ifreq);

  20.  
  21. while (intrface-- > 0)

  22. {

  23. if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface])))

  24. {

  25. ip=(inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));

  26. break;

  27. }

  28. }

  29. }

  30. close (fd);

  31. return ip;

  32. }

  33. }

猜你喜欢

转载自blog.csdn.net/sinat_41625153/article/details/82799957
今日推荐