简体   繁体   中英

Get IP address of interface in Linux using pcap

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM