@@ -974,3 +974,45 @@ PTF_TEST_CASE(TestSolarisSnoopFileRead)
974
974
975
975
readerDev.close ();
976
976
} // TestSolarisSnoopFileRead
977
+
978
+ PTF_TEST_CASE (TestPcapFileWriterDeviceDestructor)
979
+ {
980
+ std::array<uint8_t , 16 > testPayload = { 0x00 , 0x01 , 0x02 , 0x03 , 0x04 , 0x05 , 0x06 , 0x07 ,
981
+ 0x08 , 0x09 , 0x0A , 0x0B , 0x0C , 0x0D , 0x0E , 0x0F };
982
+ pcpp::RawPacket rawPacket1 (testPayload.data (), testPayload.size (), timeval{}, false );
983
+ pcpp::RawPacket rawPacket2 (testPayload.data (), testPayload.size (), timeval{}, false );
984
+
985
+ // Create some pcaps in a nested scope to test cleanup on destruction.
986
+ {
987
+ // create a file to leave open on destruction. If close is properly done on destruction, the contents & size of
988
+ // this file should match the next explicitly closed file.
989
+ pcpp::PcapFileWriterDevice writerDevDestructorNoClose (EXAMPLE_PCAP_DESTRUCTOR1_PATH, pcpp::LINKTYPE_ETHERNET,
990
+ false );
991
+ PTF_ASSERT_TRUE (writerDevDestructorNoClose.open ());
992
+ PTF_ASSERT_TRUE (writerDevDestructorNoClose.writePacket (rawPacket1));
993
+ PTF_ASSERT_TRUE (writerDevDestructorNoClose.writePacket (rawPacket2));
994
+
995
+ // create a file that will be explicitly closed before construction
996
+ pcpp::PcapFileWriterDevice writerDevDestructorExplicitClose (EXAMPLE_PCAP_DESTRUCTOR2_PATH,
997
+ pcpp::LINKTYPE_ETHERNET, false );
998
+ PTF_ASSERT_TRUE (writerDevDestructorExplicitClose.open ());
999
+ PTF_ASSERT_TRUE (writerDevDestructorExplicitClose.writePacket (rawPacket1));
1000
+ PTF_ASSERT_TRUE (writerDevDestructorExplicitClose.writePacket (rawPacket2));
1001
+ writerDevDestructorExplicitClose.close ();
1002
+ }
1003
+
1004
+ // Check that file sizes are equal. This should fail if the pcpp::PcapFileWriterDevice destructor does not close
1005
+ // properly.
1006
+ std::ifstream fileDestructorNoClose (EXAMPLE_PCAP_DESTRUCTOR1_PATH, std::ios::binary | std::ios::in);
1007
+ fileDestructorNoClose.seekg (0 , std::ios::end);
1008
+ auto posNoClose = fileDestructorNoClose.tellg ();
1009
+
1010
+ std::ifstream fileDestructorExplicitClose (EXAMPLE_PCAP_DESTRUCTOR2_PATH, std::ios::binary | std::ios::in);
1011
+ fileDestructorExplicitClose.seekg (0 , std::ios::end);
1012
+ auto posExplicitClose = fileDestructorExplicitClose.tellg ();
1013
+
1014
+ // sizes should be non-zero and match if files both got closed properly
1015
+ PTF_ASSERT_NOT_EQUAL (0 , posNoClose);
1016
+ PTF_ASSERT_NOT_EQUAL (0 , posExplicitClose);
1017
+ PTF_ASSERT_EQUAL (posNoClose, posExplicitClose);
1018
+ } // TestPcapFileWriterDeviceDestructor
0 commit comments