Crizly
Crizly

Reputation: 1009

Find Single Interface IP address (libpcap)

I'm trying to extract a single IP address for a single interface, i've got this to print out all of the IP addresses for all the interfaces and tried to do

if (d->name == en0) {
    char myip = inet_ntoa(((struct sockaddr_in*)a->addr)->sin_addr);
    // print myip
 }

But it just returns null. I'm not all that familiar with C unfortunately, how can I extract the IP address based on the interface name?

static char errbuf[PCAP_ERRBUF_SIZE];

void getInterfaces()
{
char myip;
pcap_if_t *alldevs;
int status = pcap_findalldevs(&alldevs, errbuf);

if(status != 0)
{
    printf("%s\n", errbuf);
}

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

----Console:-----------------------------------------------
en0: 192.168.56.1
awdl0:
bridge0:
tun0: 10.20.30.40
en1:
en2:
p2p0:
lo0: 127.0.0.1

Upvotes: 1

Views: 414

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

char myip = inet_ntoa(((struct sockaddr_in*)a->addr)->sin_addr);

inet_ntoa returns a char * (not a char), change to:

char *myip = inet_ntoa(((struct sockaddr_in*)a->addr)->sin_addr);

This line is also wrong:

if (d->name == en0) {

you want:

if (strcmp(d->name, "en0") == 0) {

Upvotes: 1

Related Questions