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

问题描述

比方说,我正在一个叫IpAddresses.c程序。我想这个程序获得根据每个接口该器件具有的所有IP地址。就像。我该怎么做?

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?

我不知道很多关于,但我读它可能会帮助我。

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

推荐答案

只需使用的。这里有一个例子:

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->sa_family==AF_INET) {
            sa = (struct sockaddr_in *) ifa->ifa_addr;
            addr = inet_ntoa(sa->sin_addr);
            printf("Interface: %s\tAddress: %s\n", 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地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 10:45