hostip.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include "socket.h"
  2. #include "hostip.h"
  3. #include <util/system/defaults.h>
  4. #include <util/system/byteorder.h>
  5. #if defined(_unix_) || defined(_cygwin_)
  6. #include <netdb.h>
  7. #endif
  8. #if !defined(BIND_LIB)
  9. #if !defined(__FreeBSD__) && !defined(_win32_) && !defined(_cygwin_)
  10. #define AGENT_USE_GETADDRINFO
  11. #endif
  12. #if defined(__FreeBSD__)
  13. #define AGENT_USE_GETADDRINFO
  14. #endif
  15. #endif
  16. int NResolver::GetHostIP(const char* hostname, ui32* ip, size_t* slots) {
  17. size_t i = 0;
  18. size_t ipsFound = 0;
  19. #ifdef AGENT_USE_GETADDRINFO
  20. int ret = 0;
  21. struct addrinfo hints;
  22. memset(&hints, 0, sizeof(hints));
  23. hints.ai_family = AF_INET;
  24. hints.ai_socktype = SOCK_STREAM;
  25. struct addrinfo* gai_res = nullptr;
  26. int gai_ret = getaddrinfo(hostname, nullptr, &hints, &gai_res);
  27. if (gai_ret == 0 && gai_res->ai_addr) {
  28. struct addrinfo* cur = gai_res;
  29. for (i = 0; i < *slots && cur; i++, cur = cur->ai_next, ipsFound++) {
  30. ip[i] = *(ui32*)(&((sockaddr_in*)(cur->ai_addr))->sin_addr);
  31. }
  32. } else {
  33. if (gai_ret == EAI_NONAME || gai_ret == EAI_SERVICE) {
  34. ret = HOST_NOT_FOUND;
  35. } else {
  36. ret = GetDnsError();
  37. }
  38. }
  39. if (gai_res) {
  40. freeaddrinfo(gai_res);
  41. }
  42. if (ret) {
  43. return ret;
  44. }
  45. #else
  46. hostent* hostent = gethostbyname(hostname);
  47. if (!hostent)
  48. return GetDnsError();
  49. if (hostent->h_addrtype != AF_INET || (unsigned)hostent->h_length < sizeof(ui32))
  50. return HOST_NOT_FOUND;
  51. char** cur = hostent->h_addr_list;
  52. for (i = 0; i < *slots && *cur; i++, cur++, ipsFound++)
  53. ip[i] = *(ui32*)*cur;
  54. #endif
  55. for (i = 0; i < ipsFound; i++) {
  56. ip[i] = InetToHost(ip[i]);
  57. }
  58. *slots = ipsFound;
  59. return 0;
  60. }
  61. int NResolver::GetDnsError() {
  62. return h_errno;
  63. }