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)));
46 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE 51 if (pcap_set_immediate_mode(m_pcap, 1) < 0)
52 BOOST_THROW_EXCEPTION(
Error(
"pcap_set_immediate_mode failed"));
64 int ret = pcap_activate(m_pcap);
66 BOOST_THROW_EXCEPTION(
Error(
"pcap_activate: " + std::string(pcap_statustostr(ret))));
68 if (pcap_set_datalink(m_pcap, dlt) < 0)
71 if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
87 int fd = pcap_get_selectable_fd(m_pcap);
89 BOOST_THROW_EXCEPTION(
Error(
"pcap_get_selectable_fd failed"));
99 return pcap_geterr(m_pcap);
106 if (pcap_stats(m_pcap, &ps) < 0)
119 int ret = pcap_setfilter(m_pcap, &prog);
120 pcap_freecode(&prog);
125 std::tuple<const uint8_t*, size_t, std::string>
129 const uint8_t* packet;
131 int ret = pcap_next_ex(m_pcap, &header, &packet);
135 return std::make_tuple(
nullptr, 0,
"timed out");
137 return std::make_tuple(packet, header->caplen,
"");
void setPacketFilter(const char *filter) const
Install a BPF filter on the receiving socket.
void activate(int dlt)
Start capturing packets.
#define PCAP_NETMASK_UNKNOWN
Copyright (c) 2014-2017, Regents of the University of California, Arizona Board of Regents...
Copyright (c) 2011-2015 Regents of the University of California.
void close()
Stop capturing and close the handle.
std::tuple< const uint8_t *, size_t, std::string > readNextPacket() const
Read the next packet captured on the interface.
PcapHelper(const std::string &interfaceName)
Create a libpcap context for live packet capture on a network interface.
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). ...
size_t getNDropped() const
Get the number of packets dropped by the kernel, as reported by libpcap.