forked from marcelog/SimplePcap
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSimplePcap.cpp
More file actions
91 lines (82 loc) · 2.4 KB
/
Copy pathSimplePcap.cpp
File metadata and controls
91 lines (82 loc) · 2.4 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <pcap.h>
#include <SimplePcap.h>
using namespace std;
namespace SimplePcapNs {
SimplePcap::~SimplePcap()
{
if (handle != NULL) {
pcap_close(handle);
handle = NULL;
}
}
void
SimplePcap::close()
{
if (handle != NULL) {
pcap_close(handle);
handle = NULL;
}
}
int
SimplePcap::send(string buf)
{
return pcap_inject(handle, buf.data(), buf.size());
}
Packet *
SimplePcap::get()
{
struct pcap_pkthdr header;
u_char *data = (u_char *)pcap_next(handle, &header);
if (data == NULL) {
throw GenericPcapException("pcap_next() returned null");
}
Packet *ret = new Packet(
header.caplen, header.len, header.ts.tv_sec, header.ts.tv_usec, data
);
return ret;
}
deviceList *
SimplePcap::findAllDevs()
{
deviceList *ret = new deviceList;
pcap_if_t *alldevs;
pcap_if_t *d;
char errbuf[PCAP_ERRBUF_SIZE];
if (pcap_findalldevs(&alldevs, errbuf) == -1)
{
throw GenericPcapException(string(errbuf));
}
for (d = alldevs; d != NULL; d = d->next)
{
if (d->description) {
(*ret)[d->name] = d->description;
} else {
(*ret)[d->name] = "";
}
}
pcap_freealldevs(alldevs);
return ret;
}
SimplePcap::SimplePcap(
const string& deviceName, const string& filterString, int snapLen, int timeout
) {
char errbuf[PCAP_ERRBUF_SIZE];
this->deviceName = string(deviceName);
this->filterString = string(filterString);
this->snapLen = snapLen;
handle = pcap_open_live(deviceName.c_str(), snapLen, 1, timeout, errbuf);
if (handle == NULL) {
throw CouldNotOpenDeviceException(deviceName, string(errbuf));
}
if (pcap_compile(handle, &fp, (char *)filterString.c_str(), 0, net) == -1) {
string errorString = string(pcap_geterr(handle));
pcap_close(handle);
throw FilterException(filterString, errorString);
}
if (pcap_setfilter(handle, &fp) == -1) {
string errorString = string(pcap_geterr(handle));
pcap_close(handle);
throw FilterException(filterString, errorString);
}
}
}