-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathpcap_util.c
97 lines (85 loc) · 2.13 KB
/
pcap_util.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
96
97
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <sys/time.h>
/*---------------------------------------------------------------------------*/
/* CITT CRC16 polynomial ^16 + ^12 + ^5 + 1 */
/*---------------------------------------------------------------------------*/
unsigned short crc16_add(unsigned char b, unsigned short acc)
{
/*
* acc = (unsigned char)(acc >> 8) | (acc << 8);
* acc ^= b;
* acc ^= (unsigned char)(acc & 0xff) >> 4;
* acc ^= (acc << 8) << 4;
* acc ^= ((acc & 0xff) << 4) << 1;
**/
acc ^= b;
acc = (acc >> 8) | (acc << 8);
acc ^= (acc & 0xff00) << 4;
acc ^= (acc >> 8) >> 4;
acc ^= (acc & 0xff00) >> 5;
return acc;
}
unsigned short crc16_data(const unsigned char *data, int len, unsigned short acc)
{
int i;
for (i = 0; i < len; ++i) {
acc = crc16_add(*data, acc);
++data;
}
return acc;
}
#define WRITEINT(VAL) \
valint = (int)VAL; \
fwrite((void *)&valint, sizeof(valint), 1, (FILE *)handle);
#define WRITESHORT(VAL) \
valshort = (short)VAL; \
fwrite((void *)&valshort, sizeof(valshort), 1, (FILE *)handle);
void pcap_write(void *handle, const uint8_t *buf, int buflen)
{
struct timeval tv;
int valint;
unsigned short crc;
if (!handle)
return;
crc = crc16_data((const unsigned char *)buf, buflen, 0);
memcpy((void *)&buf[buflen], &crc, 2);
buflen += 2;
gettimeofday(&tv, NULL);
WRITEINT(tv.tv_sec);
WRITEINT(tv.tv_usec);
WRITEINT(buflen);
WRITEINT(buflen);
fwrite(buf, buflen, 1, (FILE *)handle);
fflush((FILE *)handle);
}
void *pcap_init(const char *fname)
{
int valint;
short valshort;
FILE *handle;
handle = fopen(fname, "wb");
if (!handle)
return NULL;
WRITEINT(0xa1b2c3d4);
WRITESHORT(0x0002);
WRITESHORT(0x0004);
WRITEINT(0);
WRITEINT(0);
WRITEINT(4096);
WRITEINT(195);
return (void *)handle;
}
#if 0
int main(void)
{
void *handle;
uint8_t buf[128];
handle = pcap_init("packet.pcap");
if(handle) {
pcap_write(handle, buf, sizeof(buf));
fclose(handle);
}
}
#endif