Skip to content

Commit

Permalink
Use unique_ptr and C++ casting in Examples (#1643)
Browse files Browse the repository at this point in the history
  • Loading branch information
lumiZGorlic authored Nov 20, 2024
1 parent 3929558 commit feba0b7
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 63 deletions.
6 changes: 3 additions & 3 deletions Examples/ArpSpoofing/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pcpp::MacAddress getMacAddress(const pcpp::IPv4Address& ipAddr, pcpp::PcapLiveDe

pcpp::MacAddress macSrc = pDevice->getMacAddress();
pcpp::MacAddress macDst(0xff, 0xff, 0xff, 0xff, 0xff, 0xff);
pcpp::EthLayer ethLayer(macSrc, macDst, (uint16_t)PCPP_ETHERTYPE_ARP);
pcpp::EthLayer ethLayer(macSrc, macDst, static_cast<uint16_t>(PCPP_ETHERTYPE_ARP));
pcpp::ArpLayer arpLayer(pcpp::ARP_REQUEST, pDevice->getMacAddress(), pDevice->getMacAddress(),
pDevice->getIPv4Address(), ipAddr);

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

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

// Create ARP reply for the victim
pcpp::Packet victimArpReply(500);
pcpp::EthLayer victimEthLayer(deviceMacAddress, victimMacAddr, (uint16_t)PCPP_ETHERTYPE_ARP);
pcpp::EthLayer victimEthLayer(deviceMacAddress, victimMacAddr, static_cast<uint16_t>(PCPP_ETHERTYPE_ARP));
pcpp::ArpLayer victimArpLayer(pcpp::ARP_REPLY, pDevice->getMacAddress(), victimMacAddr, gatewayAddr, victimAddr);
victimArpReply.addLayer(&victimEthLayer);
victimArpReply.addLayer(&victimArpLayer);
Expand Down
2 changes: 1 addition & 1 deletion Examples/Arping/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ void listInterfaces()
*/
void onApplicationInterrupted(void* cookie)
{
auto shouldStop = (bool*)cookie;
auto shouldStop = static_cast<bool*>(cookie);
*shouldStop = true;
}

Expand Down
22 changes: 12 additions & 10 deletions Examples/HttpAnalyzer/HttpStatsCollector.h
Original file line number Diff line number Diff line change
Expand Up @@ -347,9 +347,9 @@ class HttpStatsCollector
if (m_FlowTable.size() != 0)
{
m_GeneralStats.averageAmountOfDataPerFlow =
(double)m_GeneralStats.amountOfHttpTraffic / (double)m_FlowTable.size();
static_cast<double>(m_GeneralStats.amountOfHttpTraffic) / static_cast<double>(m_FlowTable.size());
m_GeneralStats.averageNumOfPacketsPerFlow =
(double)m_GeneralStats.numOfHttpPackets / (double)m_FlowTable.size();
static_cast<double>(m_GeneralStats.numOfHttpPackets) / static_cast<double>(m_FlowTable.size());
}

return hashVal;
Expand Down Expand Up @@ -419,7 +419,8 @@ class HttpStatsCollector
// calc average transactions per flow
if (m_FlowTable.size() != 0)
m_GeneralStats.averageNumOfHttpTransactionsPerFlow =
(double)m_GeneralStats.numOfHttpTransactions / (double)m_FlowTable.size();
static_cast<double>(m_GeneralStats.numOfHttpTransactions) /
static_cast<double>(m_FlowTable.size());
}

// set last seen sequence number
Expand All @@ -435,8 +436,8 @@ class HttpStatsCollector
m_RequestStats.numOfMessages++;
m_RequestStats.totalMessageHeaderSize += req->getHeaderLen();
if (m_RequestStats.numOfMessages != 0)
m_RequestStats.averageMessageHeaderSize =
(double)m_RequestStats.totalMessageHeaderSize / (double)m_RequestStats.numOfMessages;
m_RequestStats.averageMessageHeaderSize = static_cast<double>(m_RequestStats.totalMessageHeaderSize) /
static_cast<double>(m_RequestStats.numOfMessages);

// extract hostname and add to hostname count map
pcpp::HeaderField* hostField = req->getFieldByName(PCPP_HTTP_HOST_FIELD);
Expand All @@ -454,8 +455,8 @@ class HttpStatsCollector
m_ResponseStats.numOfMessages++;
m_ResponseStats.totalMessageHeaderSize += res->getHeaderLen();
if (m_ResponseStats.numOfMessages != 0)
m_ResponseStats.averageMessageHeaderSize =
(double)m_ResponseStats.totalMessageHeaderSize / (double)m_ResponseStats.numOfMessages;
m_ResponseStats.averageMessageHeaderSize = static_cast<double>(m_ResponseStats.totalMessageHeaderSize) /
static_cast<double>(m_ResponseStats.numOfMessages);

// extract content-length (if exists)
pcpp::HeaderField* contentLengthField = res->getFieldByName(PCPP_HTTP_CONTENT_LENGTH_FIELD);
Expand All @@ -464,8 +465,9 @@ class HttpStatsCollector
m_ResponseStats.numOfMessagesWithContentLength++;
m_ResponseStats.totalContentLengthSize += atoi(contentLengthField->getFieldValue().c_str());
if (m_ResponseStats.numOfMessagesWithContentLength != 0)
m_ResponseStats.averageContentLengthSize = (double)m_ResponseStats.totalContentLengthSize /
(double)m_ResponseStats.numOfMessagesWithContentLength;
m_ResponseStats.averageContentLengthSize =
static_cast<double>(m_ResponseStats.totalContentLengthSize) /
static_cast<double>(m_ResponseStats.numOfMessagesWithContentLength);
}

// extract content-type and add to content-type map
Expand Down Expand Up @@ -497,7 +499,7 @@ class HttpStatsCollector

gettimeofday(&tv, nullptr);

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

HttpGeneralStats m_GeneralStats;
Expand Down
17 changes: 7 additions & 10 deletions Examples/HttpAnalyzer/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* For more details about modes of operation and parameters run HttpAnalyzer -h
*/

#include <memory>
#include <iomanip>
#include <algorithm>
#include "PcapLiveDeviceList.h"
Expand Down Expand Up @@ -150,7 +151,7 @@ void httpPacketArrive(pcpp::RawPacket* packet, pcpp::PcapLiveDevice* dev, void*
// parse the packet
pcpp::Packet parsedPacket(packet);

HttpPacketArrivedData* data = (HttpPacketArrivedData*)cookie;
HttpPacketArrivedData* data = static_cast<HttpPacketArrivedData*>(cookie);

// give the packet to the collector
data->statsCollector->collectStats(&parsedPacket);
Expand Down Expand Up @@ -392,7 +393,7 @@ void printCurrentRates(HttpStatsCollector& collector)
*/
void onApplicationInterrupted(void* cookie)
{
bool* shouldStop = (bool*)cookie;
bool* shouldStop = static_cast<bool*>(cookie);
*shouldStop = true;
}

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

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

// close input file
reader->close();

// free reader memory
delete reader;
}

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

// if needed to save the captured packets to file - open a writer device
pcpp::PcapFileWriterDevice* pcapWriter = nullptr;
std::unique_ptr<pcpp::PcapFileWriterDevice> pcapWriter;
if (savePacketsToFileName != "")
{
pcapWriter = new pcpp::PcapFileWriterDevice(savePacketsToFileName);
pcapWriter.reset(new pcpp::PcapFileWriterDevice(savePacketsToFileName));
if (!pcapWriter->open())
{
EXIT_WITH_ERROR("Could not open pcap file for writing");
Expand All @@ -461,7 +459,7 @@ void analyzeHttpFromLiveTraffic(pcpp::PcapLiveDevice* dev, bool printRatesPeriod
HttpPacketArrivedData data;
HttpStatsCollector collector(dstPort);
data.statsCollector = &collector;
data.pcapWriter = pcapWriter;
data.pcapWriter = pcapWriter.get();
dev->startCapture(httpPacketArrive, &data);

// register the on app close event to print summary stats on app termination
Expand Down Expand Up @@ -495,7 +493,6 @@ void analyzeHttpFromLiveTraffic(pcpp::PcapLiveDevice* dev, bool printRatesPeriod
if (pcapWriter != nullptr)
{
pcapWriter->close();
delete pcapWriter;
}
}

Expand Down
48 changes: 22 additions & 26 deletions Examples/PcapSplitter/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
*/

#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <RawPacket.h>
Expand Down Expand Up @@ -294,66 +295,67 @@ int main(int argc, char* argv[])
EXIT_WITH_ERROR("Split method was not given");
}

Splitter* splitter = nullptr;
std::unique_ptr<Splitter> splitter;

// decide of the splitter to use, according to the user's choice
if (method == SPLIT_BY_FILE_SIZE)
{
uint64_t paramAsUint64 = (paramWasSet ? strtoull(param, nullptr, 10) : 0);
splitter = new FileSizeSplitter(paramAsUint64);
splitter.reset(new FileSizeSplitter(paramAsUint64));
}
else if (method == SPLIT_BY_PACKET_COUNT)
{
int paramAsInt = (paramWasSet ? atoi(param) : 0);
splitter = new PacketCountSplitter(paramAsInt);
splitter.reset(new PacketCountSplitter(paramAsInt));
}
else if (method == SPLIT_BY_IP_CLIENT)
{
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
splitter = new ClientIPSplitter(paramAsInt);
splitter.reset(new ClientIPSplitter(paramAsInt));
}
else if (method == SPLIT_BY_IP_SERVER)
{
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
splitter = new ServerIPSplitter(paramAsInt);
splitter.reset(new ServerIPSplitter(paramAsInt));
}
else if (method == SPLIT_BY_SERVER_PORT)
{
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
splitter = new ServerPortSplitter(paramAsInt);
splitter.reset(new ServerPortSplitter(paramAsInt));
}
else if (method == SPLIT_BY_CLIENT_PORT)
{
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
splitter = new ClientPortSplitter(paramAsInt);
splitter.reset(new ClientPortSplitter(paramAsInt));
}
else if (method == SPLIT_BY_2_TUPLE)
{
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
splitter = new TwoTupleSplitter(paramAsInt);
splitter.reset(new TwoTupleSplitter(paramAsInt));
}
else if (method == SPLIT_BY_5_TUPLE)
{
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
splitter = new FiveTupleSplitter(paramAsInt);
splitter.reset(new FiveTupleSplitter(paramAsInt));
}
else if (method == SPLIT_BY_BPF_FILTER)
{
splitter = new BpfCriteriaSplitter(std::string(param));
splitter.reset(new BpfCriteriaSplitter(std::string(param)));
}
else if (method == SPLIT_BY_ROUND_ROBIN)
{
int paramAsInt = (paramWasSet ? atoi(param) : 0);
splitter = new RoundRobinSplitter(paramAsInt);
splitter.reset(new RoundRobinSplitter(paramAsInt));
}
else
{
EXIT_WITH_ERROR("Unknown method '" << method << "'");
}

// verify splitter param is legal, otherwise return an error
std::string errorStr;
if (!splitter->isSplitterParamLegal(errorStr))
{
delete splitter;
EXIT_WITH_ERROR(errorStr);
}

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

// open a pcap file for reading
pcpp::IFileReaderDevice* reader = pcpp::IFileReaderDevice::getReader(inputPcapFileName);
bool isReaderPcapng = (dynamic_cast<pcpp::PcapNgFileReaderDevice*>(reader) != nullptr);
std::unique_ptr<pcpp::IFileReaderDevice> reader(pcpp::IFileReaderDevice::getReader(inputPcapFileName));
bool isReaderPcapng = (dynamic_cast<pcpp::PcapNgFileReaderDevice*>(reader.get()) != nullptr);

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

// prepare a map of file number to IFileWriterDevice
std::unordered_map<int, pcpp::IFileWriterDevice*> outputFiles;
std::unordered_map<int, std::unique_ptr<pcpp::IFileWriterDevice>> outputFiles;

// read all packets from input file, for each packet do:
while (reader->getNextPacket(rawPacket))
Expand All @@ -411,12 +413,12 @@ int main(int argc, char* argv[])
if (isReaderPcapng)
{
// if reader is pcapng, create a pcapng writer
outputFiles[fileNum] = new pcpp::PcapNgFileWriterDevice(fileName);
outputFiles[fileNum].reset(new pcpp::PcapNgFileWriterDevice(fileName));
}
else
{
// if reader is pcap, create a pcap writer
outputFiles[fileNum] = new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType());
outputFiles[fileNum].reset(new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType()));
}

// open the writer
Expand All @@ -438,12 +440,12 @@ int main(int argc, char* argv[])
if (isReaderPcapng)
{
// if reader is pcapng, create a pcapng writer
outputFiles[fileNum] = new pcpp::PcapNgFileWriterDevice(fileName);
outputFiles[fileNum].reset(new pcpp::PcapNgFileWriterDevice(fileName));
}
else
{
// if reader is pcap, create a pcap writer
outputFiles[fileNum] = new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType());
outputFiles[fileNum].reset(new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType()));
}

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

// free the writer memory and put null in the map record
delete outputFiles[fileId];
outputFiles[fileId] = nullptr;
outputFiles[fileId].reset();
}
}

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

// free reader memory
delete reader;
delete splitter;

// close the writer files which are still open
for (const auto& it : outputFiles)
{
if (it.second != nullptr)
{
it.second->close();
delete it.second;
}
}

Expand Down
6 changes: 3 additions & 3 deletions Examples/SSLAnalyzer/SSLStatsCollector.h
Original file line number Diff line number Diff line change
Expand Up @@ -302,9 +302,9 @@ class SSLStatsCollector
if (m_FlowTable.size() != 0)
{
m_GeneralStats.averageAmountOfDataPerFlow =
(double)m_GeneralStats.amountOfSSLTraffic / (double)m_FlowTable.size();
static_cast<double>(m_GeneralStats.amountOfSSLTraffic) / static_cast<double>(m_FlowTable.size());
m_GeneralStats.averageNumOfPacketsPerFlow =
(double)m_GeneralStats.numOfSSLPackets / (double)m_FlowTable.size();
static_cast<double>(m_GeneralStats.numOfSSLPackets) / static_cast<double>(m_FlowTable.size());
}

return hashVal;
Expand Down Expand Up @@ -406,7 +406,7 @@ class SSLStatsCollector

gettimeofday(&tv, nullptr);

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

SSLGeneralStats m_GeneralStats;
Expand Down
Loading

0 comments on commit feba0b7

Please sign in to comment.