获取使用的getaddrinfo()C函数的本地IP地址? [英] Obtaining local IP address using getaddrinfo() C function?

查看:1033
本文介绍了获取使用的getaddrinfo()C函数的本地IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用的getaddrinfo()函数来获取我的本地(不是外部)的IP地址,但我看到的例子中提供的此处,他们在那里为我的需求太复杂了。还看到了其他职位,其中大部分确实想获得外部IP,而不是本地的。

I'm trying to obtain my local (not the external) IP address using the getaddrinfo() function, but I saw the examples provided here, and they where too complex for my needs. Also saw other posts and most of them really wanted to get the external IP, not the local one.

任何人都可以提供有关如何使用这一功能以获得自己的本地IP地址,一个简单的例子,一个链接(或一个简单的例子)?

Could anyone provide a link to a simple example (or a simple example) about how to obtain my own local IP address using this function ?

只是要清楚,当我说的地方,如果路由器是 192.168.0.1 ,我的本地IP地址可以是类似 192.168.0 .X (只是一个例子)。

Just to be clear when I say local, if a router is 192.168.0.1 , my local IP address could be something like 192.168.0.x ( just an example ).

推荐答案

的getaddrinfo()不是获取你的本地IP地址 - 这是用于查找名称和/或服务的套接字地址。为了获得本地IP地址(ES),你想要的功能是 getifaddrs() - 这里有一个小例子:

getaddrinfo() isn't for obtaining your local IP address - it's for looking up names and/or services to socket addresses. To obtain the local IP address(es), the function you want is getifaddrs() - here's a minimal example:

#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;
}

这篇关于获取使用的getaddrinfo()C函数的本地IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆