28 #include <pcap/pcap.h> 31 #if !defined(PCAP_NETMASK_UNKNOWN) 32 #define PCAP_NETMASK_UNKNOWN 0xffffffff 41 char errbuf[PCAP_ERRBUF_SIZE] = {};
42 m_pcap = pcap_create(interfaceName.data(), errbuf);
44 BOOST_THROW_EXCEPTION(
Error(
"pcap_create: " + std::string(errbuf)));
50 if (pcap_set_immediate_mode(m_pcap, 1) < 0)
51 BOOST_THROW_EXCEPTION(
Error(
"pcap_set_immediate_mode failed"));
62 int ret = pcap_activate(m_pcap);
64 BOOST_THROW_EXCEPTION(
Error(
"pcap_activate: " + std::string(pcap_statustostr(ret))));
66 if (pcap_set_datalink(m_pcap, dlt) < 0)
69 if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
85 int fd = pcap_get_selectable_fd(m_pcap);
87 BOOST_THROW_EXCEPTION(
Error(
"pcap_get_selectable_fd failed"));
97 return pcap_geterr(m_pcap);
104 if (pcap_stats(m_pcap, &ps) < 0)
117 int ret = pcap_setfilter(m_pcap, &prog);
118 pcap_freecode(&prog);
123 std::tuple<const uint8_t*, size_t, std::string>
127 const uint8_t* packet;
129 int ret = pcap_next_ex(m_pcap, &header, &packet);
133 return std::make_tuple(
nullptr, 0,
"timed out");
135 return std::make_tuple(packet, header->caplen,
"");
void activate(int dlt)
Start capturing packets.
#define PCAP_NETMASK_UNKNOWN
void setPacketFilter(const char *filter) const
Install a BPF filter on the receiving socket.
Copyright (c) 2011-2015 Regents of the University of California.
std::string getLastError() const
Get last error message.
void close()
Stop capturing and close the handle.
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).
size_t getNDropped() const
Get the number of packets dropped by the kernel, as reported by libpcap.
std::tuple< const uint8_t *, size_t, std::string > readNextPacket() const
Read the next packet captured on the interface.