ip.hpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #pragma once
  2. #include <sys/types.h>
  3. #include <ifaddrs.h>
  4. #include <netinet/in.h>
  5. #include <arpa/inet.h>
  6. #include <string.h>
  7. #include <iostream>
  8. #include <vector>
  9. class INetInfo {
  10. public:
  11. static std::vector<std::string> getIpv4List() {
  12. return getIpList();
  13. }
  14. static std::vector<std::string> getIpv6List() {
  15. return getIpList(AF_INET6);
  16. }
  17. private:
  18. static std::vector<std::string> getIpList(int ipv4_6 = AF_INET) {
  19. int ret_val = 0;
  20. std::vector<std::string> ip_list;
  21. struct ifaddrs * ifAddrStruct = NULL;
  22. void * tmpAddrPtr = NULL;
  23. // 1.
  24. ret_val = getifaddrs(&ifAddrStruct);
  25. if (0 != ret_val) {
  26. ret_val = errno;
  27. return ip_list;
  28. }
  29. // 2.
  30. std::string str_ipvX;
  31. int padress_buf_len = 0;
  32. char addressBuffer[INET6_ADDRSTRLEN] = {0};
  33. if (AF_INET6 == ipv4_6)
  34. padress_buf_len = INET6_ADDRSTRLEN;
  35. else
  36. padress_buf_len = INET_ADDRSTRLEN;
  37. while (NULL != ifAddrStruct )
  38. {
  39. if (ipv4_6 == ifAddrStruct->ifa_addr->sa_family )
  40. {
  41. // is a valid IP4 Address
  42. tmpAddrPtr = &((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
  43. inet_ntop(ipv4_6, tmpAddrPtr, addressBuffer, padress_buf_len);
  44. str_ipvX = std::string(addressBuffer);
  45. ip_list.push_back(str_ipvX);
  46. memset(addressBuffer, 0, padress_buf_len);
  47. }
  48. ifAddrStruct=ifAddrStruct->ifa_next;
  49. }
  50. return ip_list;
  51. }
  52. };