Pejman Moghadam / C-programming

C - Determine network and netmask address using pcap

Public domain


/* gcc -lpcap pcap_lookupnet.c */
#include   <pcap.h>
#include   <arpa/inet.h>
#include   <stdlib.h>

int main()
{
        char errbuf[PCAP_ERRBUF_SIZE];
        char dev[]="eth0";
        char *net_quad;
        char *mask_quad;
        bpf_u_int32 net_bin;
        bpf_u_int32 mask_bin;
        struct in_addr addr;

        printf("IF: %s\n", dev);

        /* ask pcap to determine the IPv4 network number
         * and mask associated with the network device
         * in binary format
         */
        if(pcap_lookupnet(dev,&net_bin,&mask_bin,errbuf) == -1 ) {
                printf("%s\n",errbuf);
                exit(EXIT_FAILURE);
        }

        /* Convert binary net to quad-dotted-decimal */
        addr.s_addr = net_bin;
        if ((net_quad=inet_ntoa(addr)) == NULL) {
                perror("inet_ntoa");
                exit(EXIT_FAILURE);
        }
        printf("NET: %s\n", net_quad);

        /* Convert binary mask to quad-dotted-decimal */
        addr.s_addr = mask_bin;
        if ((mask_quad=inet_ntoa(addr)) == NULL) {
                perror("inet_ntoa");
                exit(EXIT_FAILURE);
        }
        printf("MASK: %s\n", net_quad);

        exit(EXIT_SUCCESS);
}

BY: Pejman Moghadam
TAG: c, pcap
DATE: 2011-02-23 17:08:00


Pejman Moghadam / C-programming [ TXT ]