| 7 | using namespace xop; |
| 8 | |
| 9 | std::string NetInterface::GetLocalIPAddress() |
| 10 | { |
| 11 | #if defined(__linux) || defined(__linux__) |
| 12 | SOCKET sockfd = 0; |
| 13 | char buf[512] = { 0 }; |
| 14 | struct ifconf ifconf; |
| 15 | struct ifreq *ifreq; |
| 16 | sockfd = socket(AF_INET, SOCK_DGRAM, 0); |
| 17 | if (sockfd == INVALID_SOCKET) |
| 18 | { |
| 19 | close(sockfd); |
| 20 | return "0.0.0.0"; |
| 21 | } |
| 22 | |
| 23 | ifconf.ifc_len = 512; |
| 24 | ifconf.ifc_buf = buf; |
| 25 | if (ioctl(sockfd, SIOCGIFCONF, &ifconf) < 0) |
| 26 | { |
| 27 | close(sockfd); |
| 28 | return "0.0.0.0"; |
| 29 | } |
| 30 | |
| 31 | close(sockfd); |
| 32 | |
| 33 | ifreq = (struct ifreq*)ifconf.ifc_buf; |
| 34 | for (int i = (ifconf.ifc_len / sizeof(struct ifreq)); i>0; i--) |
| 35 | { |
| 36 | if (ifreq->ifr_flags == AF_INET) |
| 37 | { |
| 38 | if (strcmp(ifreq->ifr_name, "lo") != 0) |
| 39 | { |
| 40 | return inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr); |
| 41 | } |
| 42 | ifreq++; |
| 43 | } |
| 44 | } |
| 45 | return "0.0.0.0"; |
| 46 | #elif defined(WIN32) || defined(_WIN32) |
| 47 | PIP_ADAPTER_INFO pIpAdapterInfo = new IP_ADAPTER_INFO(); |
| 48 | unsigned long size = sizeof(IP_ADAPTER_INFO); |
| 49 | |
| 50 | int ret = GetAdaptersInfo(pIpAdapterInfo, &size); |
| 51 | if (ret == ERROR_BUFFER_OVERFLOW) |
| 52 | { |
| 53 | delete pIpAdapterInfo; |
| 54 | pIpAdapterInfo = (PIP_ADAPTER_INFO)new BYTE[size]; |
| 55 | ret = GetAdaptersInfo(pIpAdapterInfo, &size); |
| 56 | } |
| 57 | |
| 58 | if (ret != ERROR_SUCCESS) |
| 59 | { |
| 60 | delete pIpAdapterInfo; |
| 61 | return "0.0.0.0"; |
| 62 | } |
| 63 | |
| 64 | while (pIpAdapterInfo) |
| 65 | { |
| 66 | IP_ADDR_STRING *pIpAddrString = &(pIpAdapterInfo->IpAddressList); |
nothing calls this directly
no outgoing calls
no test coverage detected