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

Gol*_*les 16 c c++ getaddrinfo

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

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

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

caf*_*caf 33

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

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <ifaddrs.h>
#include <errno.h>

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这是我在这个问题上见过的最好的答案。 (2认同)