3

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.

BSMP
  • 4,596
  • 8
  • 33
  • 44
Jan
  • 1,054
  • 13
  • 36
  • 2
    I don't get it. why do you want to do it with pcap? – Karoly Horvath Feb 25 '12 at 10:47
  • because I'm curious, also I've seen that example(and others) where is written and it actually gives them their network address and that is maybe not what they wanted, and then someone who will read it and learn from it (like me) will get confused. However I don't mind using the code from the first link. As I said it would be nice to have such solution, not only for my but also for other people that will(are) learning pcap. – Jan Feb 25 '12 at 10:57

1 Answers1

11

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
  • Thanks. I had a problem with the compiler that I solved this way: http://stackoverflow.com/questions/24881/how-do-i-fix-for-loop-initial-declaration-used-outside-c99-mode-gcc-error – tremendows Jul 11 '13 at 16:15