31 #include <pcap/pcap.h>
34 #if !defined(PCAP_NETMASK_UNKNOWN)
35 #define PCAP_NETMASK_UNKNOWN 0xffffffff
44 char errbuf[PCAP_ERRBUF_SIZE] = {};
45 m_pcap = pcap_create(interfaceName.data(), errbuf);
47 NDN_THROW(
Error(
"pcap_create: " + std::string(errbuf)));
53 if (pcap_set_immediate_mode(m_pcap, 1) < 0)
54 NDN_THROW(
Error(
"pcap_set_immediate_mode failed"));
56 pcap_set_snaplen(m_pcap, ethernet::HDR_LEN + ndn::MAX_NDN_PACKET_SIZE);
57 pcap_set_buffer_size(m_pcap, 4 * 1024 * 1024);
69 int ret = pcap_activate(m_pcap);
71 NDN_THROW(
Error(
"pcap_activate: " + std::string(pcap_statustostr(ret))));
74 if (pcap_set_datalink(m_pcap, dlt) < 0)
77 if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
93 int fd = pcap_get_selectable_fd(m_pcap);
95 NDN_THROW(
Error(
"pcap_get_selectable_fd failed"));
105 return pcap_geterr(m_pcap);
112 if (pcap_stats(m_pcap, &ps) < 0)
125 int ret = pcap_setfilter(m_pcap, &prog);
126 pcap_freecode(&prog);
131 std::tuple<span<const uint8_t>, std::string>
135 const uint8_t* packet;
137 int ret = pcap_next_ex(m_pcap, &header, &packet);
141 return {span<uint8_t>{},
"timed out"};
143 return {{packet, header->caplen},
""};
static void runElevated(F &&f)
PcapHelper(const std::string &interfaceName)
Create a libpcap context for live packet capture on a network interface.
int getFd() const
Obtain a file descriptor that can be used in calls such as select(2) and poll(2).
std::string getLastError() const noexcept
Get last error message.
void activate(int dlt)
Start capturing packets.
size_t getNDropped() const
Get the number of packets dropped by the kernel, as reported by libpcap.
void setPacketFilter(const char *filter) const
Install a BPF filter on the receiving socket.
std::tuple< span< const uint8_t >, std::string > readNextPacket() const noexcept
Read the next packet captured on the interface.
void close() noexcept
Stop capturing and close the handle.
Copyright (c) 2014-2015, Regents of the University of California, Arizona Board of Regents,...
#define PCAP_NETMASK_UNKNOWN