使用getaddrinfo()C函数获取本地IP地址?

我正在尝试使用getaddrinfo()函数获取我的本地(而不是外部)IP地址,但我看到了这里提供的示例,而且它们对我的需求来说过于复杂。 还看到了其他post,其中大部分都非常想获得外部IP,而不是本地IP。

任何人都可以提供一个关于如何使用此function获取我自己的本地IP地址的简单示例(或简单示例)的链接?

为了清楚当我说本地时,如果路由器是192.168.0.1 ,我的本地IP地址可能是192.168.0.x (只是一个例子)。

getaddrinfo()不是用于获取本地IP地址 – 它用于查找套接字地址的名称和/或服务。 要获取本地IP地址,您需要的function是getifaddrs() – 这是一个最小的例子:

 #include  #include  #include  #include  #include  #include  #include  #include  #include  int main(int argc, char *argv[]) { struct ifaddrs *myaddrs, *ifa; void *in_addr; char buf[64]; if(getifaddrs(&myaddrs) != 0) { perror("getifaddrs"); exit(1); } for (ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if (!(ifa->ifa_flags & IFF_UP)) continue; switch (ifa->ifa_addr->sa_family) { case AF_INET: { struct sockaddr_in *s4 = (struct sockaddr_in *)ifa->ifa_addr; in_addr = &s4->sin_addr; break; } case AF_INET6: { struct sockaddr_in6 *s6 = (struct sockaddr_in6 *)ifa->ifa_addr; in_addr = &s6->sin6_addr; break; } default: continue; } if (!inet_ntop(ifa->ifa_addr->sa_family, in_addr, buf, sizeof(buf))) { printf("%s: inet_ntop failed!\n", ifa->ifa_name); } else { printf("%s: %s\n", ifa->ifa_name, buf); } } freeifaddrs(myaddrs); return 0; } 

使用gethostname()后传递主机名到gethostbyname()

 int gethostname(char *hostname, size_t size);