#include <iostream>
#include <string>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <netdb.h>
std::string GetIp() {
void *tmpAddrPtr = NULL;
struct ifaddrs *ifAddrStruct = NULL;
getifaddrs(&ifAddrStruct);
std::string valid_ip;
while (ifAddrStruct != NULL) {
if (ifAddrStruct->ifa_addr->sa_family == AF_INET) {
tmpAddrPtr = &(reinterpret_cast<struct sockaddr_in *>(ifAddrStruct->ifa_addr))->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
// std::cout << "Check out ip4: " << ifAddrStruct->ifa_name << ":" << addressBuffer << std::endl;
std::string str = addressBuffer;
if (str.substr(0, 1) != "0" && str.substr(0, 3) != "127" && str.substr(0, 3) != "172") {
valid_ip = str;
break;
}
}
valid_ip = "get invalid ip ...";
ifAddrStruct = ifAddrStruct->ifa_next;
}
//std::cout << "valid_ip: " << valid_ip << std::endl;
return valid_ip;
}
int main(){
std::cout << GetIp() << std::endl;
}