12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- #pragma once
- #include <sys/types.h>
- #include <ifaddrs.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <string.h>
- #include <iostream>
- #include <vector>
- class INetInfo {
- public:
- static std::vector<std::string> getIpv4List() {
- return getIpList();
- }
- static std::vector<std::string> getIpv6List() {
- return getIpList(AF_INET6);
- }
- private:
- static std::vector<std::string> getIpList(int ipv4_6 = AF_INET) {
- int ret_val = 0;
- std::vector<std::string> ip_list;
- struct ifaddrs * ifAddrStruct = NULL;
- void * tmpAddrPtr = NULL;
- // 1.
- ret_val = getifaddrs(&ifAddrStruct);
- if (0 != ret_val) {
- ret_val = errno;
- return ip_list;
- }
- // 2.
- std::string str_ipvX;
- int padress_buf_len = 0;
- char addressBuffer[INET6_ADDRSTRLEN] = {0};
- if (AF_INET6 == ipv4_6)
- padress_buf_len = INET6_ADDRSTRLEN;
- else
- padress_buf_len = INET_ADDRSTRLEN;
- while (NULL != ifAddrStruct )
- {
- if (ipv4_6 == ifAddrStruct->ifa_addr->sa_family )
- {
- // is a valid IP4 Address
- tmpAddrPtr = &((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
- inet_ntop(ipv4_6, tmpAddrPtr, addressBuffer, padress_buf_len);
- str_ipvX = std::string(addressBuffer);
- ip_list.push_back(str_ipvX);
- memset(addressBuffer, 0, padress_buf_len);
- }
- ifAddrStruct=ifAddrStruct->ifa_next;
- }
- return ip_list;
- }
- };
|