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,
"");
PcapHelper(const std::string &interfaceName)
Create a libpcap context for live packet capture on a network interface.
#define PCAP_NETMASK_UNKNOWN
Copyright (c) 2014-2017, Regents of the University of California, Arizona Board of Regents...
size_t getNDropped() const
Get the number of packets dropped by the kernel, as reported by libpcap.
std::string getLastError() const
Get last error message.
Copyright (c) 2014-2015, Regents of the University of California, Arizona Board of Regents...
std::tuple< const uint8_t *, size_t, std::string > readNextPacket() const
Read the next packet captured on the interface.
void activate(int dlt)
Start capturing packets.
int getFd() const
Obtain a file descriptor that can be used in calls such as select(2) and poll(2). ...
void close()
Stop capturing and close the handle.
void setPacketFilter(const char *filter) const
Install a BPF filter on the receiving socket.