Skip to content

Commit feba0b7

Browse files
authored
Use unique_ptr and C++ casting in Examples (seladb#1643)
1 parent 3929558 commit feba0b7

File tree

7 files changed

+55
-63
lines changed

7 files changed

+55
-63
lines changed

Examples/ArpSpoofing/main.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ pcpp::MacAddress getMacAddress(const pcpp::IPv4Address& ipAddr, pcpp::PcapLiveDe
6565

6666
pcpp::MacAddress macSrc = pDevice->getMacAddress();
6767
pcpp::MacAddress macDst(0xff, 0xff, 0xff, 0xff, 0xff, 0xff);
68-
pcpp::EthLayer ethLayer(macSrc, macDst, (uint16_t)PCPP_ETHERTYPE_ARP);
68+
pcpp::EthLayer ethLayer(macSrc, macDst, static_cast<uint16_t>(PCPP_ETHERTYPE_ARP));
6969
pcpp::ArpLayer arpLayer(pcpp::ARP_REQUEST, pDevice->getMacAddress(), pDevice->getMacAddress(),
7070
pDevice->getIPv4Address(), ipAddr);
7171

@@ -136,15 +136,15 @@ void doArpSpoofing(pcpp::PcapLiveDevice* pDevice, const pcpp::IPv4Address& gatew
136136

137137
// Create ARP reply for the gateway
138138
pcpp::Packet gwArpReply(500);
139-
pcpp::EthLayer gwEthLayer(deviceMacAddress, gatewayMacAddr, (uint16_t)PCPP_ETHERTYPE_ARP);
139+
pcpp::EthLayer gwEthLayer(deviceMacAddress, gatewayMacAddr, static_cast<uint16_t>(PCPP_ETHERTYPE_ARP));
140140
pcpp::ArpLayer gwArpLayer(pcpp::ARP_REPLY, pDevice->getMacAddress(), gatewayMacAddr, victimAddr, gatewayAddr);
141141
gwArpReply.addLayer(&gwEthLayer);
142142
gwArpReply.addLayer(&gwArpLayer);
143143
gwArpReply.computeCalculateFields();
144144

145145
// Create ARP reply for the victim
146146
pcpp::Packet victimArpReply(500);
147-
pcpp::EthLayer victimEthLayer(deviceMacAddress, victimMacAddr, (uint16_t)PCPP_ETHERTYPE_ARP);
147+
pcpp::EthLayer victimEthLayer(deviceMacAddress, victimMacAddr, static_cast<uint16_t>(PCPP_ETHERTYPE_ARP));
148148
pcpp::ArpLayer victimArpLayer(pcpp::ARP_REPLY, pDevice->getMacAddress(), victimMacAddr, gatewayAddr, victimAddr);
149149
victimArpReply.addLayer(&victimEthLayer);
150150
victimArpReply.addLayer(&victimArpLayer);

Examples/Arping/main.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ void listInterfaces()
101101
*/
102102
void onApplicationInterrupted(void* cookie)
103103
{
104-
auto shouldStop = (bool*)cookie;
104+
auto shouldStop = static_cast<bool*>(cookie);
105105
*shouldStop = true;
106106
}
107107

Examples/HttpAnalyzer/HttpStatsCollector.h

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -347,9 +347,9 @@ class HttpStatsCollector
347347
if (m_FlowTable.size() != 0)
348348
{
349349
m_GeneralStats.averageAmountOfDataPerFlow =
350-
(double)m_GeneralStats.amountOfHttpTraffic / (double)m_FlowTable.size();
350+
static_cast<double>(m_GeneralStats.amountOfHttpTraffic) / static_cast<double>(m_FlowTable.size());
351351
m_GeneralStats.averageNumOfPacketsPerFlow =
352-
(double)m_GeneralStats.numOfHttpPackets / (double)m_FlowTable.size();
352+
static_cast<double>(m_GeneralStats.numOfHttpPackets) / static_cast<double>(m_FlowTable.size());
353353
}
354354

355355
return hashVal;
@@ -419,7 +419,8 @@ class HttpStatsCollector
419419
// calc average transactions per flow
420420
if (m_FlowTable.size() != 0)
421421
m_GeneralStats.averageNumOfHttpTransactionsPerFlow =
422-
(double)m_GeneralStats.numOfHttpTransactions / (double)m_FlowTable.size();
422+
static_cast<double>(m_GeneralStats.numOfHttpTransactions) /
423+
static_cast<double>(m_FlowTable.size());
423424
}
424425

425426
// set last seen sequence number
@@ -435,8 +436,8 @@ class HttpStatsCollector
435436
m_RequestStats.numOfMessages++;
436437
m_RequestStats.totalMessageHeaderSize += req->getHeaderLen();
437438
if (m_RequestStats.numOfMessages != 0)
438-
m_RequestStats.averageMessageHeaderSize =
439-
(double)m_RequestStats.totalMessageHeaderSize / (double)m_RequestStats.numOfMessages;
439+
m_RequestStats.averageMessageHeaderSize = static_cast<double>(m_RequestStats.totalMessageHeaderSize) /
440+
static_cast<double>(m_RequestStats.numOfMessages);
440441

441442
// extract hostname and add to hostname count map
442443
pcpp::HeaderField* hostField = req->getFieldByName(PCPP_HTTP_HOST_FIELD);
@@ -454,8 +455,8 @@ class HttpStatsCollector
454455
m_ResponseStats.numOfMessages++;
455456
m_ResponseStats.totalMessageHeaderSize += res->getHeaderLen();
456457
if (m_ResponseStats.numOfMessages != 0)
457-
m_ResponseStats.averageMessageHeaderSize =
458-
(double)m_ResponseStats.totalMessageHeaderSize / (double)m_ResponseStats.numOfMessages;
458+
m_ResponseStats.averageMessageHeaderSize = static_cast<double>(m_ResponseStats.totalMessageHeaderSize) /
459+
static_cast<double>(m_ResponseStats.numOfMessages);
459460

460461
// extract content-length (if exists)
461462
pcpp::HeaderField* contentLengthField = res->getFieldByName(PCPP_HTTP_CONTENT_LENGTH_FIELD);
@@ -464,8 +465,9 @@ class HttpStatsCollector
464465
m_ResponseStats.numOfMessagesWithContentLength++;
465466
m_ResponseStats.totalContentLengthSize += atoi(contentLengthField->getFieldValue().c_str());
466467
if (m_ResponseStats.numOfMessagesWithContentLength != 0)
467-
m_ResponseStats.averageContentLengthSize = (double)m_ResponseStats.totalContentLengthSize /
468-
(double)m_ResponseStats.numOfMessagesWithContentLength;
468+
m_ResponseStats.averageContentLengthSize =
469+
static_cast<double>(m_ResponseStats.totalContentLengthSize) /
470+
static_cast<double>(m_ResponseStats.numOfMessagesWithContentLength);
469471
}
470472

471473
// extract content-type and add to content-type map
@@ -497,7 +499,7 @@ class HttpStatsCollector
497499

498500
gettimeofday(&tv, nullptr);
499501

500-
return (((double)tv.tv_sec) + (double)(tv.tv_usec / 1000000.0));
502+
return ((static_cast<double>(tv.tv_sec)) + static_cast<double>(tv.tv_usec / 1000000.0));
501503
}
502504

503505
HttpGeneralStats m_GeneralStats;

Examples/HttpAnalyzer/main.cpp

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
* For more details about modes of operation and parameters run HttpAnalyzer -h
1818
*/
1919

20+
#include <memory>
2021
#include <iomanip>
2122
#include <algorithm>
2223
#include "PcapLiveDeviceList.h"
@@ -150,7 +151,7 @@ void httpPacketArrive(pcpp::RawPacket* packet, pcpp::PcapLiveDevice* dev, void*
150151
// parse the packet
151152
pcpp::Packet parsedPacket(packet);
152153

153-
HttpPacketArrivedData* data = (HttpPacketArrivedData*)cookie;
154+
HttpPacketArrivedData* data = static_cast<HttpPacketArrivedData*>(cookie);
154155

155156
// give the packet to the collector
156157
data->statsCollector->collectStats(&parsedPacket);
@@ -392,7 +393,7 @@ void printCurrentRates(HttpStatsCollector& collector)
392393
*/
393394
void onApplicationInterrupted(void* cookie)
394395
{
395-
bool* shouldStop = (bool*)cookie;
396+
bool* shouldStop = static_cast<bool*>(cookie);
396397
*shouldStop = true;
397398
}
398399

@@ -402,7 +403,7 @@ void onApplicationInterrupted(void* cookie)
402403
void analyzeHttpFromPcapFile(const std::string& pcapFileName, uint16_t dstPort)
403404
{
404405
// open input file (pcap or pcapng file)
405-
pcpp::IFileReaderDevice* reader = pcpp::IFileReaderDevice::getReader(pcapFileName);
406+
std::unique_ptr<pcpp::IFileReaderDevice> reader(pcpp::IFileReaderDevice::getReader(pcapFileName));
406407

407408
if (!reader->open())
408409
EXIT_WITH_ERROR("Could not open input pcap file");
@@ -427,9 +428,6 @@ void analyzeHttpFromPcapFile(const std::string& pcapFileName, uint16_t dstPort)
427428

428429
// close input file
429430
reader->close();
430-
431-
// free reader memory
432-
delete reader;
433431
}
434432

435433
/**
@@ -447,10 +445,10 @@ void analyzeHttpFromLiveTraffic(pcpp::PcapLiveDevice* dev, bool printRatesPeriod
447445
EXIT_WITH_ERROR("Could not set up filter on device");
448446

449447
// if needed to save the captured packets to file - open a writer device
450-
pcpp::PcapFileWriterDevice* pcapWriter = nullptr;
448+
std::unique_ptr<pcpp::PcapFileWriterDevice> pcapWriter;
451449
if (savePacketsToFileName != "")
452450
{
453-
pcapWriter = new pcpp::PcapFileWriterDevice(savePacketsToFileName);
451+
pcapWriter.reset(new pcpp::PcapFileWriterDevice(savePacketsToFileName));
454452
if (!pcapWriter->open())
455453
{
456454
EXIT_WITH_ERROR("Could not open pcap file for writing");
@@ -461,7 +459,7 @@ void analyzeHttpFromLiveTraffic(pcpp::PcapLiveDevice* dev, bool printRatesPeriod
461459
HttpPacketArrivedData data;
462460
HttpStatsCollector collector(dstPort);
463461
data.statsCollector = &collector;
464-
data.pcapWriter = pcapWriter;
462+
data.pcapWriter = pcapWriter.get();
465463
dev->startCapture(httpPacketArrive, &data);
466464

467465
// register the on app close event to print summary stats on app termination
@@ -495,7 +493,6 @@ void analyzeHttpFromLiveTraffic(pcpp::PcapLiveDevice* dev, bool printRatesPeriod
495493
if (pcapWriter != nullptr)
496494
{
497495
pcapWriter->close();
498-
delete pcapWriter;
499496
}
500497
}
501498

Examples/PcapSplitter/main.cpp

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
*/
4646

4747
#include <iostream>
48+
#include <memory>
4849
#include <string>
4950
#include <unordered_map>
5051
#include <RawPacket.h>
@@ -294,66 +295,67 @@ int main(int argc, char* argv[])
294295
EXIT_WITH_ERROR("Split method was not given");
295296
}
296297

297-
Splitter* splitter = nullptr;
298+
std::unique_ptr<Splitter> splitter;
298299

299300
// decide of the splitter to use, according to the user's choice
300301
if (method == SPLIT_BY_FILE_SIZE)
301302
{
302303
uint64_t paramAsUint64 = (paramWasSet ? strtoull(param, nullptr, 10) : 0);
303-
splitter = new FileSizeSplitter(paramAsUint64);
304+
splitter.reset(new FileSizeSplitter(paramAsUint64));
304305
}
305306
else if (method == SPLIT_BY_PACKET_COUNT)
306307
{
307308
int paramAsInt = (paramWasSet ? atoi(param) : 0);
308-
splitter = new PacketCountSplitter(paramAsInt);
309+
splitter.reset(new PacketCountSplitter(paramAsInt));
309310
}
310311
else if (method == SPLIT_BY_IP_CLIENT)
311312
{
312313
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
313-
splitter = new ClientIPSplitter(paramAsInt);
314+
splitter.reset(new ClientIPSplitter(paramAsInt));
314315
}
315316
else if (method == SPLIT_BY_IP_SERVER)
316317
{
317318
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
318-
splitter = new ServerIPSplitter(paramAsInt);
319+
splitter.reset(new ServerIPSplitter(paramAsInt));
319320
}
320321
else if (method == SPLIT_BY_SERVER_PORT)
321322
{
322323
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
323-
splitter = new ServerPortSplitter(paramAsInt);
324+
splitter.reset(new ServerPortSplitter(paramAsInt));
324325
}
325326
else if (method == SPLIT_BY_CLIENT_PORT)
326327
{
327328
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
328-
splitter = new ClientPortSplitter(paramAsInt);
329+
splitter.reset(new ClientPortSplitter(paramAsInt));
329330
}
330331
else if (method == SPLIT_BY_2_TUPLE)
331332
{
332333
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
333-
splitter = new TwoTupleSplitter(paramAsInt);
334+
splitter.reset(new TwoTupleSplitter(paramAsInt));
334335
}
335336
else if (method == SPLIT_BY_5_TUPLE)
336337
{
337338
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
338-
splitter = new FiveTupleSplitter(paramAsInt);
339+
splitter.reset(new FiveTupleSplitter(paramAsInt));
339340
}
340341
else if (method == SPLIT_BY_BPF_FILTER)
341342
{
342-
splitter = new BpfCriteriaSplitter(std::string(param));
343+
splitter.reset(new BpfCriteriaSplitter(std::string(param)));
343344
}
344345
else if (method == SPLIT_BY_ROUND_ROBIN)
345346
{
346347
int paramAsInt = (paramWasSet ? atoi(param) : 0);
347-
splitter = new RoundRobinSplitter(paramAsInt);
348+
splitter.reset(new RoundRobinSplitter(paramAsInt));
348349
}
349350
else
351+
{
350352
EXIT_WITH_ERROR("Unknown method '" << method << "'");
353+
}
351354

352355
// verify splitter param is legal, otherwise return an error
353356
std::string errorStr;
354357
if (!splitter->isSplitterParamLegal(errorStr))
355358
{
356-
delete splitter;
357359
EXIT_WITH_ERROR(errorStr);
358360
}
359361

@@ -362,8 +364,8 @@ int main(int argc, char* argv[])
362364
outputPcapDir + std::string(1, SEPARATOR) + getFileNameWithoutExtension(inputPcapFileName) + "-";
363365

364366
// open a pcap file for reading
365-
pcpp::IFileReaderDevice* reader = pcpp::IFileReaderDevice::getReader(inputPcapFileName);
366-
bool isReaderPcapng = (dynamic_cast<pcpp::PcapNgFileReaderDevice*>(reader) != nullptr);
367+
std::unique_ptr<pcpp::IFileReaderDevice> reader(pcpp::IFileReaderDevice::getReader(inputPcapFileName));
368+
bool isReaderPcapng = (dynamic_cast<pcpp::PcapNgFileReaderDevice*>(reader.get()) != nullptr);
367369

368370
if (reader == nullptr || !reader->open())
369371
{
@@ -387,7 +389,7 @@ int main(int argc, char* argv[])
387389
pcpp::RawPacket rawPacket;
388390

389391
// prepare a map of file number to IFileWriterDevice
390-
std::unordered_map<int, pcpp::IFileWriterDevice*> outputFiles;
392+
std::unordered_map<int, std::unique_ptr<pcpp::IFileWriterDevice>> outputFiles;
391393

392394
// read all packets from input file, for each packet do:
393395
while (reader->getNextPacket(rawPacket))
@@ -411,12 +413,12 @@ int main(int argc, char* argv[])
411413
if (isReaderPcapng)
412414
{
413415
// if reader is pcapng, create a pcapng writer
414-
outputFiles[fileNum] = new pcpp::PcapNgFileWriterDevice(fileName);
416+
outputFiles[fileNum].reset(new pcpp::PcapNgFileWriterDevice(fileName));
415417
}
416418
else
417419
{
418420
// if reader is pcap, create a pcap writer
419-
outputFiles[fileNum] = new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType());
421+
outputFiles[fileNum].reset(new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType()));
420422
}
421423

422424
// open the writer
@@ -438,12 +440,12 @@ int main(int argc, char* argv[])
438440
if (isReaderPcapng)
439441
{
440442
// if reader is pcapng, create a pcapng writer
441-
outputFiles[fileNum] = new pcpp::PcapNgFileWriterDevice(fileName);
443+
outputFiles[fileNum].reset(new pcpp::PcapNgFileWriterDevice(fileName));
442444
}
443445
else
444446
{
445447
// if reader is pcap, create a pcap writer
446-
outputFiles[fileNum] = new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType());
448+
outputFiles[fileNum].reset(new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType()));
447449
}
448450

449451
// open the writer in __append__ mode
@@ -464,8 +466,7 @@ int main(int argc, char* argv[])
464466
outputFiles[fileId]->close();
465467

466468
// free the writer memory and put null in the map record
467-
delete outputFiles[fileId];
468-
outputFiles[fileId] = nullptr;
469+
outputFiles[fileId].reset();
469470
}
470471
}
471472

@@ -478,17 +479,12 @@ int main(int argc, char* argv[])
478479
// close the reader file
479480
reader->close();
480481

481-
// free reader memory
482-
delete reader;
483-
delete splitter;
484-
485482
// close the writer files which are still open
486483
for (const auto& it : outputFiles)
487484
{
488485
if (it.second != nullptr)
489486
{
490487
it.second->close();
491-
delete it.second;
492488
}
493489
}
494490

Examples/SSLAnalyzer/SSLStatsCollector.h

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -302,9 +302,9 @@ class SSLStatsCollector
302302
if (m_FlowTable.size() != 0)
303303
{
304304
m_GeneralStats.averageAmountOfDataPerFlow =
305-
(double)m_GeneralStats.amountOfSSLTraffic / (double)m_FlowTable.size();
305+
static_cast<double>(m_GeneralStats.amountOfSSLTraffic) / static_cast<double>(m_FlowTable.size());
306306
m_GeneralStats.averageNumOfPacketsPerFlow =
307-
(double)m_GeneralStats.numOfSSLPackets / (double)m_FlowTable.size();
307+
static_cast<double>(m_GeneralStats.numOfSSLPackets) / static_cast<double>(m_FlowTable.size());
308308
}
309309

310310
return hashVal;
@@ -406,7 +406,7 @@ class SSLStatsCollector
406406

407407
gettimeofday(&tv, nullptr);
408408

409-
return (((double)tv.tv_sec) + (double)(tv.tv_usec / 1000000.0));
409+
return ((static_cast<double>(tv.tv_sec)) + static_cast<double>(tv.tv_usec / 1000000.0));
410410
}
411411

412412
SSLGeneralStats m_GeneralStats;

0 commit comments

Comments
 (0)