我怎样才能知道 C 中接口的 IP 地址? [英] How can I get to know the IP address for interfaces in C?

查看:22
本文介绍了我怎样才能知道 C 中接口的 IP 地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在运行一个名为 IpAddresses.c 的程序.我希望该程序根据每个接口获取该设备的所有 IP 地址.就像 ifconfig 一样.我该怎么做?

Let's say I'm running a program called IpAddresses.c. I want that program to get all IP addresses this device has according to each interface. Just like ifconfig. How can I do that?

我对 ioctl 了解不多,但我读过它可能对我有帮助.

I don't know much about ioctl, but I read it might help me.

推荐答案

只需使用 getifaddrs().举个例子:

Just use getifaddrs(). Here's an example:

#include <arpa/inet.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <stdio.h>

int main ()
{
    struct ifaddrs *ifap, *ifa;
    struct sockaddr_in *sa;
    char *addr;

    getifaddrs (&ifap);
    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
        if (ifa->ifa_addr && ifa->ifa_addr->sa_family==AF_INET) {
            sa = (struct sockaddr_in *) ifa->ifa_addr;
            addr = inet_ntoa(sa->sin_addr);
            printf("Interface: %s	Address: %s
", ifa->ifa_name, addr);
        }
    }

    freeifaddrs(ifap);
    return 0;
}

这是我在我的机器上得到的输出:

And here's the output I get on my machine:

Interface: lo   Address: 127.0.0.1
Interface: eth0 Address: 69.72.234.7
Interface: eth0:1       Address: 10.207.9.3

这篇关于我怎样才能知道 C 中接口的 IP 地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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