31 #include <pcap/pcap.h>
34 #if !defined(PCAP_NETMASK_UNKNOWN)
35 #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);
67 int ret = pcap_activate(m_pcap);
69 NDN_THROW(
Error(
"pcap_activate: " + std::string(pcap_statustostr(ret))));
72 char errbuf[PCAP_ERRBUF_SIZE] = {};
73 if (pcap_setnonblock(m_pcap, 1, errbuf) < 0)
74 NDN_THROW(
Error(
"pcap_setnonblock: " + std::string(errbuf)));
76 if (pcap_set_datalink(m_pcap, dlt) < 0)
79 if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
95 int fd = pcap_get_selectable_fd(m_pcap);
97 NDN_THROW(
Error(
"pcap_get_selectable_fd failed"));
107 return pcap_geterr(m_pcap);
114 if (pcap_stats(m_pcap, &ps) < 0)
127 int ret = pcap_setfilter(m_pcap, &prog);
128 pcap_freecode(&prog);
133 std::tuple<span<const uint8_t>, std::string>
137 const uint8_t* packet;
139 int ret = pcap_next_ex(m_pcap, &header, &packet);
143 return {span<uint8_t>{},
"Nothing to read"};
145 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.
#define PCAP_NETMASK_UNKNOWN