Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

c - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", 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("
");
    }

    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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...