-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbpf_socket_counter.c
More file actions
75 lines (74 loc) · 1.93 KB
/
Copy pathbpf_socket_counter.c
File metadata and controls
75 lines (74 loc) · 1.93 KB
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
#define _GNU_SOURCE
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <linux/filter.h>
#include <linux/if_ether.h>
#include <linux/if_packet.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <errno.h>
int main(int argc, char **argv)
{
#if !defined(__linux__)
fprintf(stderr, "bpf_socket_counter is Linux-only\n");
return 1;
#else
const char *ifname = argc > 1 ? argv[1] : "lo";
int s = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (s < 0) {
perror("socket");
return 1;
}
struct ifreq ifr;
memset(&ifr, 0, sizeof ifr);
strncpy(ifr.ifr_name, ifname, sizeof ifr.ifr_name - 1);
if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
perror("SIOCGIFINDEX");
close(s);
return 1;
}
struct sockaddr_ll sll;
memset(&sll, 0, sizeof sll);
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
sll.sll_protocol = htons(ETH_P_ALL);
if (bind(s, (struct sockaddr *)&sll, sizeof sll) < 0) {
perror("bind");
close(s);
return 1;
}
struct sock_filter code[] = {
BPF_STMT(BPF_RET | BPF_K, 0xFFFFFFFF)
};
struct sock_fprog prog;
prog.len = sizeof(code) / sizeof(code[0]);
prog.filter = code;
if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER, &prog, sizeof prog) < 0) {
perror("SO_ATTACH_FILTER");
close(s);
return 1;
}
printf("counting packets on %s, press Ctrl-C to stop\n", ifname);
unsigned long long count = 0;
for (;;) {
char buf[2048];
ssize_t n = recv(s, buf, sizeof buf, 0);
if (n < 0) {
if (errno == EINTR) continue;
perror("recv");
break;
}
count++;
if ((count % 100) == 0) {
printf("packets=%llu\n", count);
}
}
close(s);
return 0;
#endif
}