使用pcap获取Linux中接口的IP地址 [英] Get IP address of interface in Linux using pcap

查看:479
本文介绍了使用pcap获取Linux中接口的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以使用libpcap在Linux中获取接口的IP地址?

Is there a way how to get an IP address of an interface in Linux using libpcap?

我发现了这个, 获取Linux上接口的IP地址 ,但不使用pcap.

I have found this, Get IP address of an interface on Linux, but that doesn't use pcap.

另外,在pcap示例中,据说类似应该会获得您的IP,但它会为您提供网络地址.

Also, in the pcap examples it is said that something like this should get your IP but it gives you your network address.

推荐答案

使用pcap_findalldevs函数:

#include <pcap/pcap.h>
#include <arpa/inet.h>

static char errbuf[PCAP_ERRBUF_SIZE];

int main() {
    pcap_if_t *alldevs;
    int status = pcap_findalldevs(&alldevs, errbuf);
    if(status != 0) {
        printf("%s\n", errbuf);
        return 1;
    }

    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);
    return 0;
}

sudo ./pcap的输出:

eth0: 192.168.2.1
usbmon1:
usbmon2:
usbmon3:
usbmon4:
usbmon5:
any:
lo: 127.0.0.1

这篇关于使用pcap获取Linux中接口的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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