#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <net/ethernet.h>
#include <pcap/pcap.h>

pcap_t *open_interface(char *name)
{
   pcap_t *pd;
   char ebuf[PCAP_ERRBUF_SIZE];

   /* wywolanie funkcji pcap w celu otworzenia interfejsu w trybie odbierania */

   pd = pcap_open_live(name, 1600, 1, 100, ebuf);
   if (!pd)
         return NULL;

   return pd;
}

int read_loop(pcap_t *pd)
{
   const unsigned char *ptr;
   int size, c;
   struct pcap_pkthdr h;
   struct ether_header *hdr;

   while (1) {

         /* odczyt kolejnego dostepnego pakietu z wykorzystaniem libpcap */

         ptr = pcap_next(pd, &h);
         if (h.caplen < sizeof(struct ether_header))
               continue;

         hdr = (struct ether_header *)ptr;

         /* wydrukowanie naglowka ethernetowego */

         for (c = 0; c < ETH_ALEN; c++)
               printf("%s%02x",c == 0 ? "" : ":",hdr->ether_shost[c]);

         printf(" > ");
         for (c = 0; c < ETH_ALEN; c++)
               printf("%s%02x",c == 0 ? "" : ":",hdr->ether_dhost[c]);

         printf(" typ: %i\n", hdr->ether_type);
   }
}

int main(int argc, char **argv)
{
   pcap_t *pd;
   char *name = argv[1];

   if (!argv[1]) {
         fprintf(stderr, "Podaj nazwe interfejsu\n");
         return -1;
   }

   pd = open_interface(name);
   if (!pd) {
         fprintf(stderr, " Nie mozna otworzyc interfejsu \n");
         return -1;
   }

   if (read_loop(pd) < 0) {
         fprintf(stderr, "Blad odczytu pakietu\n");
         return -1;
   }

   return 0;
}
