Skip to content

Commit f1234fc

Browse files
author
Artiom N.
committed
Chapter 22 examples fix
1 parent 126f7db commit f1234fc

File tree

6 files changed

+60
-23
lines changed

6 files changed

+60
-23
lines changed

src/book01/ch22/cpp/pcap_sniffer/main.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ int main(int argc, const char *const argv[])
107107
}
108108

109109
// Compile the filter expression.
110-
if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1)
110+
if (-1 == pcap_compile(handle, &fp, filter_exp, 0, net))
111111
{
112112
ss << "Couldn't parse filter \"" << filter_exp << "\": " << pcap_geterr(handle) << "!" << std::endl;
113113
throw std::logic_error(ss.str());

src/book01/ch22/cpp/pcap_sniffer/packet_printer.cpp

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include <iostream>
55
#include <string>
66

7+
78
// Ethernet headers are always exactly 14 bytes.
89
constexpr auto SIZE_ETHERNET = 14;
910

@@ -99,6 +100,7 @@ struct sniff_tcp
99100
tcp_seq th_ack;
100101
// Data offset, rsvd.
101102
u_char th_offx2;
103+
// cppcheck-suppress unusedStructMember
102104
tcp_flags th_flags;
103105
u_short th_win;
104106
u_short th_sum;
@@ -160,15 +162,15 @@ void PacketPrinter::print_hex_ascii_line(const u_char *payload, int len, int off
160162
void PacketPrinter::print_payload(const u_char *payload, int len)
161163
{
162164
int len_rem = len;
163-
// number of bytes per line.
164-
int line_width = 16;
165-
// zero-based offset counter.
165+
// Number of bytes per line.
166+
constexpr int line_width = 16;
167+
// Zero-based offset counter.
166168
int offset = 0;
167169
const u_char *ch = payload;
168170

169171
if (len <= 0) return;
170172

171-
/* data fits on one line */
173+
// Data fits on one line.
172174
if (len <= line_width)
173175
{
174176
print_hex_ascii_line(ch, len, offset);
@@ -190,7 +192,7 @@ void PacketPrinter::print_payload(const u_char *payload, int len)
190192
// Check if we have line width chars or less.
191193
if (len_rem <= line_width)
192194
{
193-
/* print last line and get out */
195+
// Print last line and get out.
194196
print_hex_ascii_line(ch, len_rem, offset);
195197
break;
196198
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <pcapplusplus/IPv4Layer.h>
2+
#include <pcapplusplus/Packet.h>
3+
#include <pcapplusplus/PcapFileDevice.h>
4+
5+
#include <iostream>
6+
7+
8+
int main(int argc, char* argv[])
9+
{
10+
pcpp::PcapFileReaderDevice reader("1_packet.pcap");
11+
12+
if (!reader.open())
13+
{
14+
std::cerr << "Error opening the pcap file" << std::endl;
15+
return EXIT_FAILURE;
16+
}
17+
18+
pcpp::RawPacket rawPacket;
19+
if (!reader.getNextPacket(rawPacket))
20+
{
21+
std::cerr << "Couldn't read the first packet in the file" << std::endl;
22+
return EXIT_FAILURE;
23+
}
24+
25+
pcpp::Packet parsedPacket(&rawPacket);
26+
27+
if (parsedPacket.isPacketOfType(pcpp::IPv4))
28+
{
29+
pcpp::IPv4Address srcIP = parsedPacket.getLayerOfType<pcpp::IPv4Layer>()->getSrcIPv4Address();
30+
pcpp::IPv4Address destIP = parsedPacket.getLayerOfType<pcpp::IPv4Layer>()->getDstIPv4Address();
31+
32+
std::cout << "Source IP is '" << srcIP << "'; Dest IP is '" << destIP << "'" << std::endl;
33+
}
34+
35+
reader.close();
36+
37+
return EXIT_SUCCESS;
38+
}

src/book01/ch22/cpp/raw_sniffer/sniffer.cpp

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#include "sniffer.h"
22

33
#include <algorithm>
4+
#include <array>
45
#include <cerrno>
56
#include <chrono>
67
#include <iostream>
@@ -191,21 +192,21 @@ bool Sniffer::capture()
191192
{
192193
// First 14 bytes are a fake ethernet header with IPv4 as the protocol.
193194
// `char` type is using for the compatibility with Windows.
194-
char buffer[BUFFER_SIZE_HDR + BUFFER_SIZE_PKT] = {0};
195-
// 0x08 - IP protocol type in the Ethernet frame protocolol type field (offset = 12).
196-
buffer[BUFFER_OFFSET_ETH + ethernet_proto_type_offset] = 0x08;
197-
pcap_sf_pkthdr* pkt = reinterpret_cast<struct pcap_sf_pkthdr*>(buffer);
195+
std::array<char, BUFFER_SIZE_HDR + BUFFER_SIZE_PKT> buffer;
196+
// 0x08 - IP protocol type in the Ethernet frame protocol type field (offset = 12).
197+
buffer[BUFFER_OFFSET_ETH + ethernet_proto_type_offset] = 0x08; // cppcheck-suppress containerOutOfBounds
198+
pcap_sf_pkthdr* pkt = reinterpret_cast<pcap_sf_pkthdr*>(buffer.data());
198199

199200
// Read the next packet, blocking forever.
200-
int rc = recv(sock_, buffer + BUFFER_WRITE_OFFSET, BUFFER_SIZE_IP, 0);
201+
const int rc = recv(sock_, buffer.data() + BUFFER_WRITE_OFFSET, BUFFER_SIZE_IP, 0);
201202

202203
if (INVALID_SOCKET == rc)
203204
{
204205
std::cerr << "recv() failed: " << sock_wrap_.get_last_error_string() << std::endl;
205206
return false;
206207
}
207208

208-
// End of file for some strange reason, so stop reading packets.
209+
// Data receiving error, so stop reading packets.
209210
if (!rc) return false;
210211

211212
std::cout << rc << " bytes received..." << std::endl;
@@ -224,7 +225,7 @@ bool Sniffer::capture()
224225
pkt->len = rc + BUFFER_ADD_HEADER_SIZE;
225226

226227
// Write packet.
227-
of_.write(reinterpret_cast<const char*>(buffer), rc + BUFFER_SIZE_HDR + BUFFER_ADD_HEADER_SIZE);
228+
of_.write(buffer.data(), rc + BUFFER_SIZE_HDR + BUFFER_ADD_HEADER_SIZE);
228229
of_.flush();
229230

230231
return true;

src/book01/ch22/python/promisc_switcher/promisc_switcher.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,17 @@ class InterfacePromiscSwitcher(ctypes.Structure):
1515

1616
def __init__(self, if_name: str, *args, **kw):
1717
super().__init__(*args, **kw)
18-
self._sock: socket.socket
19-
if 'socket' in kw:
20-
self._sock = kw['socket']
21-
else:
22-
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
18+
self._sock = kw['socket'] if 'socket' in kw else socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2319

2420
self.ifr_ifrn = if_name.encode()
2521

2622
@property
2723
def socket(self) -> socket.socket | None:
28-
return self._sock
24+
return self._sock # type: ignore
2925

3026
def set_promisc(self):
3127
sock = self._sock
32-
if sys.platform == 'win32':
28+
if 'win32' == sys.platform:
3329
sock.bind((self.ifr_ifrn, 0))
3430
sock.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
3531
else:
@@ -38,8 +34,8 @@ def set_promisc(self):
3834
ioctl(sock.fileno(), self.SIOCSIFFLAGS, self)
3935

4036
def unset_promisc(self, close_socket: bool = True):
41-
if sys.platform == 'win32':
42-
self._sock.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
37+
if 'win32' == sys.platform:
38+
self._sock.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) # type: ignore[attr-defined]
4339
else:
4440
self.ifr_flags &= ~self.IFF_PROMISC # pylint: disable=E1101(no-member)
4541
ioctl(self._sock.fileno(), self.SIOCSIFFLAGS, self)

src/book01/ch22/python/python-sniffer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def payload_offset(self) -> int:
5757

5858
@final
5959
@classmethod
60-
def unpack_packet(cls, base_protocol, packet, skip_channel_proto_check: bool = False) -> list[Any]:
60+
def unpack_packet(cls, base_protocol, packet, *, skip_channel_proto_check: bool = False) -> list[Any]:
6161
"""Package unpacking method."""
6262
if not issubclass(base_protocol, NetworkProtocolHeader):
6363
raise TypeError(

0 commit comments

Comments
 (0)