Code:
#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/if_ether.h>
void parse_ether(const struct pcap_pkthdr* pkthdr,const u_char*
packet)
{
int i;
int len=(*pkthdr).len;
struct ethhdr *ethernet_header;
unsigned char *p;
if(len>sizeof(struct ethhdr))
{
ethernet_header=(struct ethhdr *)(packet);
p=ethernet_header->h_dest;
printf("Destination MAC : ");
for(i=0;i<6;i++)
{
printf("%.2x ", *p);
p++;
}
p=ethernet_header->h_source;
printf("\n");
printf("Source MAC : ");
for(i=0;i<6;i++)
{
printf("%.2x ", *p);
p++;
}
p=(void *)ðernet_header->h_proto;
printf("\n");
printf("Protocol");
for(i=0;i<2;i++)
{
printf("%.2x ", *p);
p++;
}
}
}
void my_callback(u_char *useless,const struct pcap_pkthdr* pkthdr,const u_char *packet)
{
int i;
u_char *ptr;
ptr=packet;
i=(*pkthdr).len;
printf("\nThe length of the Packet is %d",i);
// Yay Display my packet in hex
while(i--)
{
printf("%.2x ", *ptr);
ptr++;
}
parse_ether(pkthdr,packet);
printf("NEXT PACKET \n\n\n");
printf("-----------------------------------------------------------------------------------------------")
}
int main()
{
int cnt; //to hold number of packets you want to capture
const u_char *packet;
struct pcap_pkthdr hdr;
u_char *ptr;
char errbuf[PCAP_ERRBUF_SIZE]; //to hold the error
pcap_t *descr;
char *dev; //to hold the name of the device
printf("Enter the number of packets you wish to capture :\n");
scanf("%d",&cnt);
dev=pcap_lookupdev(errbuf); //get the name of the device
if(dev==NULL) // Didnt get any device
{
printf("device error%s",errbuf);
exit(1);
}
//open the device for listening
descr=pcap_open_live(dev,BUFSIZ,1,-1,errbuf);
if(descr==NULL) //check for an error
{
printf("pcap_open_live %s",errbuf);
exit(1);
}
//capture packets until cnt number of packets captured
pcap_loop(descr,cnt,my_callback,NULL); //loop calls function my_callback
printf("Exit Now");
return 0;
}