-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsniffer.c
102 lines (70 loc) · 1.52 KB
/
sniffer.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/if_ether.h>
void callback(u_char *args, const struct pcap_pkthdr* pkthdr, const u_char* packet)
{
int i = 0;
static int count = 0;
printf("Packet Count: %d\n", ++count);
printf("Recieved Packet size : %d\n", pkthdr->len);
printf("Payload:\n");
for (i =0; i<pkthdr->len; i++)
{
if (isprint(packet[i]))
printf("%c ", packet[i]);
else
printf(" . ");
if((i%16==0 && i!=0)|| i == pkthdr->len-1)
printf("\n");
}
}
int main(int argc, char **argv)
{
int i;
char *dev;
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t* descr;
const u_char *packet;
struct pcap_pkthdr hdr;
struct ether_header *eptr;
struct bpf_program fp;
bpf_u_int32 maskp;
bpf_u_int32 netp;
if(argc != 2)
{
fprintf(stdout, "Usage: %s \"expression\"\n", argv[0]);
return 0;
}
/*Get a device*/
dev = pcap_lookupdev(errbuf);
if (dev == NULL)
{
fprintf(stderr, "%s\n",errbuf);
exit(1);
}
/*Get network addr and mask*/
pcap_lookupnet(dev, &netp, &maskp, errbuf);
descr = pcap_open_live(dev, BUFSIZ, 1, -1, errbuf);
if(descr == NULL)
{
printf("pcap_open_live():%s\n", errbuf);
exit(1);
}
if(pcap_compile(descr,&fp, argv[1], 0, netp) == -1)
{
fprintf(stderr, "Error calling pcap_compile\n");
exit(1);
}
if(pcap_setfilter(descr,&fp) == -1)
{
fprintf(stderr, "Error setting filter!\n");
exit(1);
}
pcap_loop(descr,-1, callback, NULL);
return 0;
}