Get IP address of interface in Linux using pcap

痴心易碎 提交于 2019-12-05 18:49:04

Using the pcap_findalldevs function:

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

Output of sudo ./pcap:

eth0: 192.168.2.1
usbmon1:
usbmon2:
usbmon3:
usbmon4:
usbmon5:
any:
lo: 127.0.0.1
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!