Advertisement
Guest User

Untitled

a guest
May 24th, 2016
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1.  
  2. #define ENABLE_AUTODETECT_INTERNAL_IP
  3. bool GetIPInfo()
  4. {
  5. #ifndef __WIN32__
  6. struct ifaddrs* ifaddrp = NULL;
  7.  
  8. if (0 != getifaddrs(&ifaddrp))
  9. return false;
  10.  
  11. for( struct ifaddrs* ifap=ifaddrp ; NULL != ifap ; ifap = ifap->ifa_next )
  12. {
  13. struct sockaddr_in * sai = (struct sockaddr_in *) ifap->ifa_addr;
  14.  
  15. if (!ifap->ifa_netmask || // ignore if no netmask
  16. sai->sin_addr.s_addr == 0 || // ignore if address is 0.0.0.0
  17. sai->sin_addr.s_addr == 16777343) // ignore if address is 127.0.0.1
  18. continue;
  19. #else
  20. WSADATA wsa_data;
  21. char host_name[100];
  22. HOSTENT* host_ent;
  23. int n = 0;
  24.  
  25. if (WSAStartup(0x0101, &wsa_data)) {
  26. return false;
  27. }
  28.  
  29. gethostname(host_name, sizeof(host_name));
  30. host_ent = gethostbyname(host_name);
  31. if (host_ent == NULL) {
  32. return false;
  33. }
  34. for ( ; host_ent->h_addr_list[n] != NULL; ++n) {
  35. struct sockaddr_in addr;
  36. struct sockaddr_in* sai = &addr;
  37. memcpy(&sai->sin_addr.s_addr, host_ent->h_addr_list[n], host_ent->h_length);
  38. #endif
  39.  
  40. char * netip = inet_ntoa(sai->sin_addr);
  41.  
  42. if (!strncmp(netip, "192.168", 7)) // ignore if address is starting with 192
  43. {
  44. strlcpy(g_szInternalIP, netip, sizeof(g_szInternalIP));
  45. #ifndef __WIN32__
  46. fprintf(stderr, "INTERNAL_IP: %s interface %s\n", netip, ifap->ifa_name);
  47. #else
  48. fprintf(stderr, "INTERNAL_IP: %s\n", netip);
  49. #endif
  50. }
  51. else if (!strncmp(netip, "10.", 3))
  52. {
  53. strlcpy(g_szInternalIP, netip, sizeof(g_szInternalIP));
  54. #ifndef __WIN32__
  55. fprintf(stderr, "INTERNAL_IP: %s interface %s\n", netip, ifap->ifa_name);
  56. #else
  57. fprintf(stderr, "INTERNAL_IP: %s\n", netip);
  58. #endif
  59. }
  60. else if (g_szPublicIP[0] == '0')
  61. {
  62. strlcpy(g_szPublicIP, netip, sizeof(g_szPublicIP));
  63. #ifndef __WIN32__
  64. fprintf(stderr, "PUBLIC_IP: %s interface %s\n", netip, ifap->ifa_name);
  65. #else
  66. fprintf(stderr, "PUBLIC_IP: %s\n", netip);
  67. #endif
  68. }
  69. }
  70.  
  71. #ifndef __WIN32__
  72. freeifaddrs( ifaddrp );
  73. #else
  74. WSACleanup();
  75. #endif
  76.  
  77. if (g_szPublicIP[0] != '0')
  78. return true;
  79. else
  80. {
  81. #ifdef ENABLE_AUTODETECT_INTERNAL_IP
  82. if (g_szInternalIP[0] == '0')
  83. return false;
  84. else
  85. strlcpy(g_szPublicIP, g_szInternalIP, sizeof(g_szPublicIP));
  86. return true;
  87. #else
  88. return false;
  89. #endif
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement