查找单接口IP地址(libpcap)

时间:2015-04-10 11:10:53

标签: c network-programming libpcap

我正在尝试为单个接口提取单个IP地址,我已经打印出所有接口的所有IP地址并试图这样做

if (d->name == en0) {
    char myip = inet_ntoa(((struct sockaddr_in*)a->addr)->sin_addr);
    // print myip
 }

但它只返回null。不幸的是,我不熟悉C,如何根据接口名称提取IP地址?

static char errbuf[PCAP_ERRBUF_SIZE];

void getInterfaces()
{
char myip;
pcap_if_t *alldevs;
int status = pcap_findalldevs(&alldevs, errbuf);

if(status != 0)
{
    printf("%s\n", errbuf);
}

for(pcap_if_t *d=alldevs; d!=NULL; d=d->next)
{
    printf("%s:", d->name);

    for(pcap_addr_t *a=d->addresses; a!=NULL; a=a->next)
    {
        if(a->addr->sa_family == AF_INET)
        {
            printf(" %s", inet_ntoa(((struct sockaddr_in*)a->addr)->sin_addr));
        }
    }
    printf("\n");
}

pcap_freealldevs(alldevs);
}

----Console:-----------------------------------------------
en0: 192.168.56.1
awdl0:
bridge0:
tun0: 10.20.30.40
en1:
en2:
p2p0:
lo0: 127.0.0.1

1 个答案:

答案 0 :(得分:1)

char myip = inet_ntoa(((struct sockaddr_in*)a->addr)->sin_addr);

inet_ntoa返回char *(不是char),更改为:

char *myip = inet_ntoa(((struct sockaddr_in*)a->addr)->sin_addr);

这一行也错了:

if (d->name == en0) {

你想要:

if (strcmp(d->name, "en0") == 0) {