#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
bool GetHostInfo(std::string &Ip)
{
struct ifaddrs *ifAddrStruct, *ifAddrStruct1;
void *tmpAddrPtr = NULL;
if (getifaddrs(&ifAddrStruct) != 0)
return false;
ifAddrStruct1 = ifAddrStruct;
while (ifAddrStruct != NULL)
{
// if (ifAddrStruct->ifa_addr->sa_family == AF_INET)
if ((ifAddrStruct->ifa_addr->sa_family == 2) &&
(!strstr(ifAddrStruct->ifa_name, "lo")) &&
(!strstr(ifAddrStruct->ifa_name, "docker")))
{
tmpAddrPtr = &((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
printf("%s IPV4 Address %s\n", ifAddrStruct->ifa_name, addressBuffer);
Ip = addressBuffer;
freeifaddrs(ifAddrStruct1); //更改为ifAddrStruct会造成内存泄露, 原因是ifAddrStruct不是真正的链表, 仅是伪链表.
return true;
}
ifAddrStruct = ifAddrStruct->ifa_next;
}
freeifaddrs(ifAddrStruct1);
return false;
}
结果:
enp0s31f6 IPV4 Address 192.168.113.193
参考