簡體   English   中英

使用getaddrinfo()C函數獲取本地IP地址?

[英]Obtaining local IP address using getaddrinfo() C function?

我正在嘗試使用getaddrinfo()函數獲取我的本地(而不是外部)IP地址,但我看到了這里提供的示例,而且它們對我的需求來說過於復雜。 還看到了其他帖子,其中大部分都非常想獲得外部IP,而不是本地IP。

任何人都可以提供一個關於如何使用此函數獲取我自己的本地IP地址的簡單示例(或簡單示例)的鏈接?

為了清楚我說本地,如果路由器是192.168.0.1 ,我的本地IP地址可能是192.168.0.x (只是一個例子)。

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

使用gethostname()后傳遞主機名到gethostbyname()

int gethostname(char *hostname, size_t size);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM