-
Notifications
You must be signed in to change notification settings - Fork 7
/
watch.c
95 lines (71 loc) · 2.2 KB
/
watch.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
86
87
88
89
90
91
92
93
94
95
#include <pcap.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
lua_State* L = NULL;
void getPacket(u_char * arg, const struct pcap_pkthdr * pkthdr, const u_char * packet) {
L = lua_open();
luaL_openlibs(L);
if (luaL_loadfile(L, "buffer.lua") || lua_pcall(L, 0,0,0))
printf("Cannot run configuration file:%s", lua_tostring(L, -1));
lua_getglobal(L, "buffer");
lua_newtable(L);
int idx = 0;
for (idx=1; idx < pkthdr->len; idx++) {
lua_pushnumber(L, idx);
lua_pushnumber(L, packet[idx]);
lua_settable(L, -3);
}
lua_pcall(L, 1,0,0);
int * id = (int *)arg;
printf("id: %d\n", ++(*id));
printf("Packet length: %d\n", pkthdr->len);
printf("Number of bytes: %d\n", pkthdr->caplen);
printf("Recieved time: %s", ctime((const time_t *)&pkthdr->ts.tv_sec));
printf("\n\n");
}
int main()
{
char errBuf[PCAP_ERRBUF_SIZE], * devStr;
/* get a device */
//devStr = pcap_lookupdev(errBuf);
devStr = "eth1";
if(devStr) {
printf("success: device: %s\n", devStr);
} else {
printf("error: %s\n", errBuf);
exit(1);
}
/* open a device, wait until a packet arrives */
pcap_t * device = pcap_open_live(devStr, 65535, 1, 0, errBuf);
if(!device) {
printf("error: pcap_open_live(): %s\n", errBuf);
exit(1);
}
L = lua_open();
luaL_openlibs(L);
if (luaL_loadfile(L, "config.lua") || lua_pcall(L, 0,1,0))
printf("Cannot run configuration file:%s", lua_tostring(L, -1));
lua_getglobal(L, "format");
lua_pcall(L, 0,1,0);
if(!lua_isstring(L, -1))
error(L, "function 'f' must return a string");
const char* format = lua_tostring(L,-1);
lua_pop(L, 1);
printf("%s\n", format);
//lua_close(L);
/* construct a filter */
struct bpf_program filter;
//pcap_compile(device, &filter, "src port 80", 1, 0);
pcap_compile(device, &filter, "dst port 80", 1, 0);
pcap_setfilter(device, &filter);
/* wait loop forever */
int id = 0;
pcap_loop(device, -1, getPacket, (u_char*)&id);
pcap_close(device);
return 0;
}