Added documentation
[ana-net.git] / opt / pfpacket-pps.c
blobc037c68519c20a3e57cf2c23420606c0ead5bc51
1 /* Compile with -lrt */
3 #include <stdio.h>
4 #include <stdint.h>
5 #include <unistd.h>
6 #include <signal.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <ctype.h>
10 #include <assert.h>
11 #include <sys/socket.h>
12 #include <sys/time.h>
13 #include <time.h>
14 #include <sys/socket.h>
15 #include <linux/if_packet.h>
16 #include <linux/if_ether.h>
17 #include <linux/if_arp.h>
18 #include <arpa/inet.h>
20 static sig_atomic_t sigint = 0;
22 static inline double timespec_to_double(const struct timespec *time)
24 return time->tv_nsec * 1E-9 + (double) time->tv_sec;
27 static void sig_handler(int sig)
29 if (sig == SIGINT)
30 sigint = 1;
33 int main(void)
35 int sock, ret;
36 char buff[1600];
37 struct timespec before, after;
38 unsigned long long pkts = 0, byte = 0;
39 double x1, x2, elapsed;
41 if (geteuid() != 0) {
42 fprintf(stderr, "Not root?!\n");
43 exit(EXIT_FAILURE);
46 signal(SIGINT, sig_handler);
48 sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
49 if (sock < 0) {
50 perror("socket");
51 return 0;
54 printf("Hit key to start!\n");
55 getchar();
56 printf("Abort with ^C\n");
58 memset(&before, 0, sizeof(before));
59 memset(&after, 0, sizeof(after));
61 clock_gettime(CLOCK_REALTIME, &before);
62 while (!sigint) {
63 ret = recv(sock, buff, sizeof(buff), 0);
64 if (ret < 0) {
65 perror("recvmsg");
66 continue;
67 } else {
68 pkts++;
69 byte += ret;
72 clock_gettime(CLOCK_REALTIME, &after);
74 x1 = timespec_to_double(&after);
75 x2 = timespec_to_double(&before);
76 elapsed = x1 - x2;
78 printf("\n\n");
79 fflush(stdout);
80 printf("time: %lf, pkts/s: %.2lf, bytes/s: %.2lf\n",
81 elapsed, 1.0 * pkts / elapsed, 1.0 * byte / elapsed);
83 close(sock);
84 return 0;