-
Notifications
You must be signed in to change notification settings - Fork 83
/
pcaputil.c
129 lines (113 loc) · 2.05 KB
/
pcaputil.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
* pcaputil.c
*
* Copyright (c) 2000 Dug Song <[email protected]>
*
* $Id: pcaputil.c,v 1.2 2001/03/15 08:33:04 dugsong Exp $
*/
#include "config.h"
#include <sys/param.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
#ifdef BSD
#include <net/bpf.h>
#include <pcap-bpf.h>
#endif
#include <pcap.h>
#include "pcaputil.h"
#ifdef BSD
static int
bpf_immediate(int fd, int on)
{
return (ioctl(fd, BIOCIMMEDIATE, &on));
}
#endif
int
pcap_dloff(pcap_t *pd)
{
int offset = -1;
switch (pcap_datalink(pd)) {
case DLT_EN10MB:
offset = 14;
break;
case DLT_IEEE802:
offset = 22;
break;
case DLT_FDDI:
offset = 21;
break;
#ifdef DLT_LOOP
case DLT_LOOP:
#endif
case DLT_NULL:
offset = 4;
break;
default:
warnx("unsupported datalink type");
break;
}
return (offset);
}
pcap_t *
pcap_init(char *intf, char *filter, int snaplen)
{
pcap_t *pd;
u_int net, mask;
struct bpf_program fcode;
char ebuf[PCAP_ERRBUF_SIZE];
if (intf == NULL && (intf = pcap_lookupdev(ebuf)) == NULL) {
warnx("%s", ebuf);
return (NULL);
}
if ((pd = pcap_open_live(intf, snaplen, 1, 512, ebuf)) == NULL) {
warnx("%s", ebuf);
return (NULL);
}
if (pcap_lookupnet(intf, &net, &mask, ebuf) == -1) {
warnx("%s", ebuf);
return (NULL);
}
if (pcap_compile(pd, &fcode, filter, 1, mask) < 0) {
pcap_perror(pd, "pcap_compile");
return (NULL);
}
if (pcap_setfilter(pd, &fcode) == -1) {
pcap_perror(pd, "pcap_compile");
return (NULL);
}
#ifdef BSD
int fd = pcap_get_selectable_fd(pd);
if (bpf_immediate(fd, 1) < 0) {
perror("ioctl");
return (NULL);
}
#endif
return (pd);
}
/* from tcpdump util.c. */
char *
copy_argv(char **argv)
{
char **p, *buf, *src, *dst;
u_int len = 0;
p = argv;
if (*p == 0)
return (0);
while (*p)
len += strlen(*p++) + 1;
if ((buf = (char *)malloc(len)) == NULL)
err(1, "copy_argv: malloc");
p = argv;
dst = buf;
while ((src = *p++) != NULL) {
while ((*dst++ = *src++) != '\0')
;
dst[-1] = ' ';
}
dst[-1] = '\0';
return (buf);
}