c++获取本地ip
#include <iostream>
#include <sys/types.h>
#include <ifaddrs.h>
#include <string>
#include <arpa/inet.h>
int main()
{
struct ifaddrs * ifAddrStruct = NULL;
struct ifaddrs * ifa = NULL;
void * tmpAddrPtr = NULL;
std::string s;
getifaddrs(&ifAddrStruct);
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)
{
if (!ifa->ifa_addr)
continue;
if (ifa->ifa_addr->sa_family == AF_INET)
{
tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
char* p = ifa->ifa_name;
if(p[0] == 'e')
s = addressBuffer;
}
}
if (ifAddrStruct != NULL)
freeifaddrs(ifAddrStruct);
std::cout << s << std::endl;
}