29 #include <pcap/pcap.h> 32 #if !defined(PCAP_NETMASK_UNKNOWN) 33 #define PCAP_NETMASK_UNKNOWN 0xffffffff 42 char errbuf[PCAP_ERRBUF_SIZE] = {};
43 m_pcap = pcap_create(interfaceName.data(), errbuf);
45 NDN_THROW(
Error(
"pcap_create: " + std::string(errbuf)));
51 if (pcap_set_immediate_mode(m_pcap, 1) < 0)
52 NDN_THROW(
Error(
"pcap_set_immediate_mode failed"));
54 pcap_set_snaplen(m_pcap, ethernet::HDR_LEN + ndn::MAX_NDN_PACKET_SIZE);
55 pcap_set_buffer_size(m_pcap, 4 * 1024 * 1024);
66 int ret = pcap_activate(m_pcap);
68 NDN_THROW(
Error(
"pcap_activate: " + std::string(pcap_statustostr(ret))));
70 if (pcap_set_datalink(m_pcap, dlt) < 0)
73 if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
89 int fd = pcap_get_selectable_fd(m_pcap);
91 NDN_THROW(
Error(
"pcap_get_selectable_fd failed"));
101 return pcap_geterr(m_pcap);
108 if (pcap_stats(m_pcap, &ps) < 0)
121 int ret = pcap_setfilter(m_pcap, &prog);
122 pcap_freecode(&prog);
127 std::tuple<const uint8_t*, size_t, std::string>
131 const uint8_t* packet;
133 int ret = pcap_next_ex(m_pcap, &header, &packet);
137 return std::make_tuple(
nullptr, 0,
"timed out");
139 return std::make_tuple(packet, header->caplen,
"");
PcapHelper(const std::string &interfaceName)
Create a libpcap context for live packet capture on a network interface.
size_t getNDropped() const
Get the number of packets dropped by the kernel, as reported by libpcap.
#define PCAP_NETMASK_UNKNOWN
void setPacketFilter(const char *filter) const
Install a BPF filter on the receiving socket.
std::tuple< const uint8_t *, size_t, std::string > readNextPacket() const
Read the next packet captured on the interface.
Copyright (c) 2014-2015, Regents of the University of California, Arizona Board of Regents...
std::string getLastError() const
Get last error message.
int getFd() const
Obtain a file descriptor that can be used in calls such as select(2) and poll(2). ...
void activate(int dlt)
Start capturing packets.
void close()
Stop capturing and close the handle.