statistics.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <math.h>
  5. #include "statistics.h"
  6. #include <sstream>
  7. #include <SQLiteCpp/SQLiteCpp.h>
  8. #include "statistics_db.h"
  9. #include "statistics.h"
  10. #include "utilities.h"
  11. using namespace Tins;
  12. /**
  13. * Checks if there is a payload and increments payloads counter.
  14. * @param pdu_l4 The packet that should be checked if it has a payload or not.
  15. */
  16. void statistics::checkPayload(const PDU *pdu_l4) {
  17. if(this->getDoExtraTests()) {
  18. // pdu_l4: Tarnsport layer 4
  19. int pktSize = pdu_l4->size();
  20. int headerSize = pdu_l4->header_size(); // TCP/UDP header
  21. int payloadSize = pktSize - headerSize;
  22. if (payloadSize > 0)
  23. payloadCount++;
  24. }
  25. }
  26. /**
  27. * Checks the correctness of TCP checksum and increments counter if the checksum was incorrect.
  28. * @param ipAddressSender The source IP.
  29. * @param ipAddressReceiver The destination IP.
  30. * @param tcpPkt The packet to get checked.
  31. */
  32. void statistics::checkTCPChecksum(std::string ipAddressSender, std::string ipAddressReceiver, TCP tcpPkt) {
  33. if(this->getDoExtraTests()) {
  34. if(check_tcpChecksum(ipAddressSender, ipAddressReceiver, tcpPkt))
  35. correctTCPChecksumCount++;
  36. else incorrectTCPChecksumCount++;
  37. }
  38. }
  39. /**
  40. * Calculates entropy of the source and destination IPs in a time interval.
  41. * @param intervalStartTimestamp The timstamp where the interval starts.
  42. * @return a vector: contains source IP entropy and destination IP entropy.
  43. */
  44. std::vector<float> statistics::calculateLastIntervalIPsEntropy(std::chrono::microseconds intervalStartTimestamp){
  45. if(this->getDoExtraTests()) {
  46. std::vector<int> IPsSrcPktsCounts;
  47. std::vector<int> IPsDstPktsCounts;
  48. std::vector<float> IPsSrcProb;
  49. std::vector<float> IPsDstProb;
  50. int pktsSent = 0, pktsReceived = 0;
  51. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  52. int indexStartSent = getClosestIndex(i->second.pkts_sent_timestamp, intervalStartTimestamp);
  53. int IPsSrcPktsCount = i->second.pkts_sent_timestamp.size() - indexStartSent;
  54. IPsSrcPktsCounts.push_back(IPsSrcPktsCount);
  55. pktsSent += IPsSrcPktsCount;
  56. int indexStartReceived = getClosestIndex(i->second.pkts_received_timestamp, intervalStartTimestamp);
  57. int IPsDstPktsCount = i->second.pkts_received_timestamp.size() - indexStartReceived;
  58. IPsDstPktsCounts.push_back(IPsDstPktsCount);
  59. pktsReceived += IPsDstPktsCount;
  60. }
  61. for (auto i = IPsSrcPktsCounts.begin(); i != IPsSrcPktsCounts.end(); i++) {
  62. IPsSrcProb.push_back((float) *i / pktsSent);
  63. }
  64. for (auto i = IPsDstPktsCounts.begin(); i != IPsDstPktsCounts.end(); i++) {
  65. IPsDstProb.push_back((float) *i / pktsReceived);
  66. }
  67. // Calculate IP source entropy
  68. float IPsSrcEntropy = 0;
  69. for (unsigned i = 0; i < IPsSrcProb.size(); i++) {
  70. if (IPsSrcProb[i] > 0)
  71. IPsSrcEntropy += -IPsSrcProb[i] * log2(IPsSrcProb[i]);
  72. }
  73. // Calculate IP destination entropy
  74. float IPsDstEntropy = 0;
  75. for (unsigned i = 0; i < IPsDstProb.size(); i++) {
  76. if (IPsDstProb[i] > 0)
  77. IPsDstEntropy += -IPsDstProb[i] * log2(IPsDstProb[i]);
  78. }
  79. std::vector<float> entropies = {IPsSrcEntropy, IPsDstEntropy};
  80. return entropies;
  81. }
  82. else {
  83. return {-1, -1};
  84. }
  85. }
  86. /**
  87. * Calculates the cumulative entropy of the source and destination IPs, i.e., the entropy for packets from the beginning of the pcap file.
  88. * @return a vector: contains the cumulative entropies of source and destination IPs
  89. */
  90. std::vector<float> statistics::calculateIPsCumEntropy(){
  91. if(this->getDoExtraTests()) {
  92. std::vector <std::string> IPs;
  93. std::vector <float> IPsSrcProb;
  94. std::vector <float> IPsDstProb;
  95. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  96. IPs.push_back(i->first);
  97. IPsSrcProb.push_back((float)i->second.pkts_sent/packetCount);
  98. IPsDstProb.push_back((float)i->second.pkts_received/packetCount);
  99. }
  100. // Calculate IP source entropy
  101. float IPsSrcEntropy = 0;
  102. for(unsigned i=0; i < IPsSrcProb.size();i++){
  103. if (IPsSrcProb[i] > 0)
  104. IPsSrcEntropy += - IPsSrcProb[i]*log2(IPsSrcProb[i]);
  105. }
  106. // Calculate IP destination entropy
  107. float IPsDstEntropy = 0;
  108. for(unsigned i=0; i < IPsDstProb.size();i++){
  109. if (IPsDstProb[i] > 0)
  110. IPsDstEntropy += - IPsDstProb[i]*log2(IPsDstProb[i]);
  111. }
  112. std::vector<float> entropies = {IPsSrcEntropy, IPsDstEntropy};
  113. return entropies;
  114. }
  115. else {
  116. return {-1, -1};
  117. }
  118. }
  119. /**
  120. * Calculates sending packet rate for each IP in a time interval. Finds min and max packet rate and adds them to ip_statistics map.
  121. * @param intervalStartTimestamp The timstamp where the interval starts.
  122. */
  123. void statistics::calculateIPIntervalPacketRate(std::chrono::duration<int, std::micro> interval, std::chrono::microseconds intervalStartTimestamp){
  124. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  125. int indexStartSent = getClosestIndex(i->second.pkts_sent_timestamp, intervalStartTimestamp);
  126. int IPsSrcPktsCount = i->second.pkts_sent_timestamp.size() - indexStartSent;
  127. float interval_pkt_rate = (float) IPsSrcPktsCount * 1000000 / interval.count(); // used 10^6 because interval in microseconds
  128. i->second.interval_pkt_rate.push_back(interval_pkt_rate);
  129. if(interval_pkt_rate > i->second.max_interval_pkt_rate || i->second.max_interval_pkt_rate == 0)
  130. i->second.max_interval_pkt_rate = interval_pkt_rate;
  131. if(interval_pkt_rate < i->second.min_interval_pkt_rate || i->second.min_interval_pkt_rate == 0)
  132. i->second.min_interval_pkt_rate = interval_pkt_rate;
  133. }
  134. }
  135. /**
  136. * Registers statistical data for a time interval.
  137. * @param intervalStartTimestamp The timstamp where the interval starts.
  138. * @param intervalEndTimestamp The timstamp where the interval ends.
  139. * @param previousPacketCount The total number of packets in last interval.
  140. */
  141. void statistics::addIntervalStat(std::chrono::duration<int, std::micro> interval, std::chrono::microseconds intervalStartTimestamp, std::chrono::microseconds intervalEndTimestamp){
  142. // Add packet rate for each IP to ip_statistics map
  143. calculateIPIntervalPacketRate(interval, intervalStartTimestamp);
  144. std::vector<float> ipEntopies = calculateLastIntervalIPsEntropy(intervalStartTimestamp);
  145. std::vector<float> ipCumEntopies = calculateIPsCumEntropy();
  146. std::string lastPktTimestamp_s = std::to_string(intervalEndTimestamp.count());
  147. std::string intervalStartTimestamp_s = std::to_string(intervalStartTimestamp.count());
  148. // The intervalStartTimestamp_s is the previous interval lastPktTimestamp_s
  149. interval_statistics[lastPktTimestamp_s].pkts_count = packetCount - intervalCumPktCount;
  150. interval_statistics[lastPktTimestamp_s].kbytes = (float(sumPacketSize - intervalCumSumPktSize) / 1024);
  151. interval_statistics[lastPktTimestamp_s].payload_count = payloadCount - intervalPayloadCount;
  152. interval_statistics[lastPktTimestamp_s].incorrect_tcp_checksum_count = incorrectTCPChecksumCount - intervalIncorrectTCPChecksumCount;
  153. interval_statistics[lastPktTimestamp_s].correct_tcp_checksum_count = correctTCPChecksumCount - intervalCorrectTCPChecksumCount;
  154. interval_statistics[lastPktTimestamp_s].novel_ip_count = ip_statistics.size() - intervalCumNewIPCount;
  155. interval_statistics[lastPktTimestamp_s].novel_ttl_count = ttl_values.size() - intervalCumNewTTLCount;
  156. interval_statistics[lastPktTimestamp_s].novel_win_size_count = win_values.size() - intervalCumNewWinSizeCount;
  157. interval_statistics[lastPktTimestamp_s].novel_tos_count = tos_values.size() - intervalCumNewToSCount;
  158. interval_statistics[lastPktTimestamp_s].novel_mss_count = mss_values.size() - intervalCumNewMSSCount;
  159. intervalPayloadCount = payloadCount;
  160. intervalIncorrectTCPChecksumCount = incorrectTCPChecksumCount;
  161. intervalCorrectTCPChecksumCount = correctTCPChecksumCount;
  162. intervalCumPktCount = packetCount;
  163. intervalCumSumPktSize = sumPacketSize;
  164. intervalCumNewIPCount = ip_statistics.size();
  165. intervalCumNewTTLCount = ttl_values.size();
  166. intervalCumNewWinSizeCount = win_values.size();
  167. intervalCumNewToSCount = tos_values.size();
  168. intervalCumNewMSSCount = mss_values.size();
  169. if(ipEntopies.size()>1){
  170. interval_statistics[lastPktTimestamp_s].ip_src_entropy = ipEntopies[0];
  171. interval_statistics[lastPktTimestamp_s].ip_dst_entropy = ipEntopies[1];
  172. }
  173. if(ipCumEntopies.size()>1){
  174. interval_statistics[lastPktTimestamp_s].ip_src_cum_entropy = ipCumEntopies[0];
  175. interval_statistics[lastPktTimestamp_s].ip_dst_cum_entropy = ipCumEntopies[1];
  176. }
  177. }
  178. /**
  179. * Registers statistical data for a sent packet in a given conversation (two IPs, two ports).
  180. * Increments the counter packets_A_B or packets_B_A.
  181. * Adds the timestamp of the packet in pkts_A_B_timestamp or pkts_B_A_timestamp.
  182. * @param ipAddressSender The sender IP address.
  183. * @param sport The source port.
  184. * @param ipAddressReceiver The receiver IP address.
  185. * @param dport The destination port.
  186. * @param timestamp The timestamp of the packet.
  187. */
  188. void statistics::addConvStat(std::string ipAddressSender,int sport,std::string ipAddressReceiver,int dport, std::chrono::microseconds timestamp){
  189. conv f1 = {ipAddressReceiver, dport, ipAddressSender, sport};
  190. conv f2 = {ipAddressSender, sport, ipAddressReceiver, dport};
  191. // if already exist A(ipAddressReceiver, dport), B(ipAddressSender, sport) conversation
  192. if (conv_statistics.count(f1)>0){
  193. conv_statistics[f1].pkts_count++;
  194. if(conv_statistics[f1].pkts_count<=3)
  195. conv_statistics[f1].interarrival_time.push_back(std::chrono::duration_cast<std::chrono::microseconds> (timestamp - conv_statistics[f1].pkts_timestamp.back()));
  196. conv_statistics[f1].pkts_timestamp.push_back(timestamp);
  197. }
  198. // Add new conversation A(ipAddressSender, sport), B(ipAddressReceiver, dport)
  199. else{
  200. conv_statistics[f2].pkts_count++;
  201. if(conv_statistics[f2].pkts_timestamp.size()>0 && conv_statistics[f2].pkts_count<=3 )
  202. conv_statistics[f2].interarrival_time.push_back(std::chrono::duration_cast<std::chrono::microseconds> (timestamp - conv_statistics[f2].pkts_timestamp.back()));
  203. conv_statistics[f2].pkts_timestamp.push_back(timestamp);
  204. }
  205. }
  206. /**
  207. * Increments the packet counter for the given IP address and MSS value.
  208. * @param ipAddress The IP address whose MSS packet counter should be incremented.
  209. * @param mssValue The MSS value of the packet.
  210. */
  211. void statistics::incrementMSScount(std::string ipAddress, int mssValue) {
  212. mss_values[mssValue]++;
  213. mss_distribution[{ipAddress, mssValue}]++;
  214. }
  215. /**
  216. * Increments the packet counter for the given IP address and window size.
  217. * @param ipAddress The IP address whose window size packet counter should be incremented.
  218. * @param winSize The window size of the packet.
  219. */
  220. void statistics::incrementWinCount(std::string ipAddress, int winSize) {
  221. win_values[winSize]++;
  222. win_distribution[{ipAddress, winSize}]++;
  223. }
  224. /**
  225. * Increments the packet counter for the given IP address and TTL value.
  226. * @param ipAddress The IP address whose TTL packet counter should be incremented.
  227. * @param ttlValue The TTL value of the packet.
  228. */
  229. void statistics::incrementTTLcount(std::string ipAddress, int ttlValue) {
  230. ttl_values[ttlValue]++;
  231. ttl_distribution[{ipAddress, ttlValue}]++;
  232. }
  233. /**
  234. * Increments the packet counter for the given IP address and ToS value.
  235. * @param ipAddress The IP address whose ToS packet counter should be incremented.
  236. * @param tosValue The ToS value of the packet.
  237. */
  238. void statistics::incrementToScount(std::string ipAddress, int tosValue) {
  239. tos_values[tosValue]++;
  240. tos_distribution[{ipAddress, tosValue}]++;
  241. }
  242. /**
  243. * Increments the protocol counter for the given IP address and protocol.
  244. * @param ipAddress The IP address whose protocol packet counter should be incremented.
  245. * @param protocol The protocol of the packet.
  246. */
  247. void statistics::incrementProtocolCount(std::string ipAddress, std::string protocol) {
  248. protocol_distribution[{ipAddress, protocol}]++;
  249. }
  250. /**
  251. * Returns the number of packets seen for the given IP address and protocol.
  252. * @param ipAddress The IP address whose packet count is wanted.
  253. * @param protocol The protocol whose packet count is wanted.
  254. * @return an integer: the number of packets
  255. */
  256. int statistics::getProtocolCount(std::string ipAddress, std::string protocol) {
  257. return protocol_distribution[{ipAddress, protocol}];
  258. }
  259. /**
  260. * Increments the packet counter for
  261. * - the given sender IP address with outgoing port and
  262. * - the given receiver IP address with incoming port.
  263. * @param ipAddressSender The IP address of the packet sender.
  264. * @param outgoingPort The port used by the sender.
  265. * @param ipAddressReceiver The IP address of the packet receiver.
  266. * @param incomingPort The port used by the receiver.
  267. */
  268. void statistics::incrementPortCount(std::string ipAddressSender, int outgoingPort, std::string ipAddressReceiver,
  269. int incomingPort) {
  270. ip_ports[{ipAddressSender, "out", outgoingPort}]++;
  271. ip_ports[{ipAddressReceiver, "in", incomingPort}]++;
  272. }
  273. /**
  274. * Creates a new statistics object.
  275. */
  276. statistics::statistics(void) {
  277. }
  278. /**
  279. * Stores the assignment IP address -> MAC address.
  280. * @param ipAddress The IP address belonging to the given MAC address.
  281. * @param macAddress The MAC address belonging to the given IP address.
  282. */
  283. void statistics::assignMacAddress(std::string ipAddress, std::string macAddress) {
  284. ip_mac_mapping[ipAddress] = macAddress;
  285. }
  286. /**
  287. * Registers statistical data for a sent packet. Increments the counter packets_sent for the sender and
  288. * packets_received for the receiver. Adds the bytes as kbytes_sent (sender) and kybtes_received (receiver).
  289. * @param ipAddressSender The IP address of the packet sender.
  290. * @param ipAddressReceiver The IP address of the packet receiver.
  291. * @param bytesSent The packet's size.
  292. */
  293. void statistics::addIpStat_packetSent(std::string filePath, std::string ipAddressSender, std::string ipAddressReceiver, long bytesSent, std::chrono::microseconds timestamp) {
  294. // Aidmar - Adding IP as a sender for first time
  295. if(ip_statistics[ipAddressSender].pkts_sent==0){
  296. // Add the IP class
  297. ip_statistics[ipAddressSender].ip_class = getIPv4Class(ipAddressSender);
  298. }
  299. // Aidmar - Adding IP as a receiver for first time
  300. if(ip_statistics[ipAddressReceiver].pkts_received==0){
  301. // Add the IP class
  302. ip_statistics[ipAddressReceiver].ip_class = getIPv4Class(ipAddressReceiver);
  303. }
  304. // Update stats for packet sender
  305. ip_statistics[ipAddressSender].kbytes_sent += (float(bytesSent) / 1024);
  306. ip_statistics[ipAddressSender].pkts_sent++;
  307. // Aidmar
  308. ip_statistics[ipAddressSender].pkts_sent_timestamp.push_back(timestamp);
  309. // Update stats for packet receiver
  310. ip_statistics[ipAddressReceiver].kbytes_received += (float(bytesSent) / 1024);
  311. ip_statistics[ipAddressReceiver].pkts_received++;
  312. // Aidmar
  313. ip_statistics[ipAddressReceiver].pkts_received_timestamp.push_back(timestamp);
  314. }
  315. /**
  316. * Setter for the timestamp_firstPacket field.
  317. * @param ts The timestamp of the first packet in the PCAP file.
  318. */
  319. void statistics::setTimestampFirstPacket(Tins::Timestamp ts) {
  320. timestamp_firstPacket = ts;
  321. }
  322. /**
  323. * Setter for the timestamp_lastPacket field.
  324. * @param ts The timestamp of the last packet in the PCAP file.
  325. */
  326. void statistics::setTimestampLastPacket(Tins::Timestamp ts) {
  327. timestamp_lastPacket = ts;
  328. }
  329. /**
  330. * Getter for the timestamp_firstPacket field.
  331. */
  332. Tins::Timestamp statistics::getTimestampFirstPacket() {
  333. return timestamp_firstPacket;
  334. }
  335. /**
  336. * Getter for the timestamp_lastPacket field.
  337. */
  338. Tins::Timestamp statistics::getTimestampLastPacket() {
  339. return timestamp_lastPacket;
  340. }
  341. /**
  342. * Getter for the packetCount field.
  343. */
  344. int statistics::getPacketCount() {
  345. return packetCount;
  346. }
  347. /**
  348. * Getter for the sumPacketSize field.
  349. */
  350. int statistics::getSumPacketSize() {
  351. return sumPacketSize;
  352. }
  353. /**
  354. * Returns the average packet size.
  355. * @return a float indicating the average packet size in kbytes.
  356. */
  357. float statistics::getAvgPacketSize() const {
  358. // AvgPktSize = (Sum of all packet sizes / #Packets)
  359. return (sumPacketSize / packetCount) / 1024;
  360. }
  361. /**
  362. * Adds the size of a packet (to be used to calculate the avg. packet size).
  363. * @param packetSize The size of the current packet in bytes.
  364. */
  365. void statistics::addPacketSize(uint32_t packetSize) {
  366. sumPacketSize += ((float) packetSize);
  367. }
  368. /**
  369. * Setter for the doExtraTests field.
  370. */
  371. void statistics::setDoExtraTests(bool var) {
  372. doExtraTests = var;
  373. }
  374. /**
  375. * Getter for the doExtraTests field.
  376. */
  377. bool statistics::getDoExtraTests() {
  378. return doExtraTests;
  379. }
  380. /**
  381. * Calculates the capture duration.
  382. * @return a formatted string HH:MM:SS.mmmmmm with
  383. * HH: hour, MM: minute, SS: second, mmmmmm: microseconds
  384. */
  385. std::string statistics::getCaptureDurationTimestamp() const {
  386. // Calculate duration
  387. time_t t = (timestamp_lastPacket.seconds() - timestamp_firstPacket.seconds());
  388. time_t ms = (timestamp_lastPacket.microseconds() - timestamp_firstPacket.microseconds());
  389. long int hour = t / 3600;
  390. long int remainder = (t - hour * 3600);
  391. long int minute = remainder / 60;
  392. long int second = (remainder - minute * 60) % 60;
  393. long int microseconds = ms;
  394. // Build desired output format: YYYY-mm-dd hh:mm:ss
  395. char out[64];
  396. sprintf(out, "%02ld:%02ld:%02ld.%06ld ", hour, minute, second, microseconds);
  397. return std::string(out);
  398. }
  399. /**
  400. * Calculates the capture duration.
  401. * @return a formatted string SS.mmmmmm with
  402. * S: seconds (UNIX time), mmmmmm: microseconds
  403. */
  404. float statistics::getCaptureDurationSeconds() const {
  405. timeval d;
  406. d.tv_sec = timestamp_lastPacket.seconds() - timestamp_firstPacket.seconds();
  407. d.tv_usec = timestamp_lastPacket.microseconds() - timestamp_firstPacket.microseconds();
  408. char tmbuf[64], buf[64];
  409. auto nowtm = localtime(&(d.tv_sec));
  410. strftime(tmbuf, sizeof(tmbuf), "%S", nowtm);
  411. snprintf(buf, sizeof(buf), "%s.%06u", tmbuf, (uint) d.tv_usec);
  412. return std::stof(std::string(buf));
  413. }
  414. /**
  415. * Creates a timestamp based on a time_t seconds (UNIX time format) and microseconds.
  416. * @param seconds
  417. * @param microseconds
  418. * @return a formatted string Y-m-d H:M:S.m with
  419. * Y: year, m: month, d: day, H: hour, M: minute, S: second, m: microseconds
  420. */
  421. std::string statistics::getFormattedTimestamp(time_t seconds, suseconds_t microseconds) const {
  422. timeval tv;
  423. tv.tv_sec = seconds;
  424. tv.tv_usec = microseconds;
  425. char tmbuf[64], buf[64];
  426. auto nowtm = localtime(&(tv.tv_sec));
  427. strftime(tmbuf, sizeof(tmbuf), "%Y-%m-%d %H:%M:%S", nowtm);
  428. snprintf(buf, sizeof(buf), "%s.%06u", tmbuf, (uint) tv.tv_usec);
  429. return std::string(buf);
  430. }
  431. /**
  432. * Calculates the statistics for a given IP address.
  433. * @param ipAddress The IP address whose statistics should be calculated.
  434. * @return a ip_stats struct containing statistical data derived by the statistical data collected.
  435. */
  436. ip_stats statistics::getStatsForIP(std::string ipAddress) {
  437. float duration = getCaptureDurationSeconds();
  438. entry_ipStat ipStatEntry = ip_statistics[ipAddress];
  439. ip_stats s;
  440. s.bandwidthKBitsIn = (ipStatEntry.kbytes_received / duration) * 8;
  441. s.bandwidthKBitsOut = (ipStatEntry.kbytes_sent / duration) * 8;
  442. s.packetPerSecondIn = (ipStatEntry.pkts_received / duration);
  443. s.packetPerSecondOut = (ipStatEntry.pkts_sent / duration);
  444. s.AvgPacketSizeSent = (ipStatEntry.kbytes_sent / ipStatEntry.pkts_sent);
  445. s.AvgPacketSizeRecv = (ipStatEntry.kbytes_received / ipStatEntry.pkts_received);
  446. return s;
  447. }
  448. /**
  449. * Increments the packet counter.
  450. */
  451. void statistics::incrementPacketCount() {
  452. packetCount++;
  453. }
  454. /**
  455. * Prints the statistics of the PCAP and IP specific statistics for the given IP address.
  456. * @param ipAddress The IP address whose statistics should be printed. Can be empty "" to print only general file statistics.
  457. */
  458. void statistics::printStats(std::string ipAddress) {
  459. std::stringstream ss;
  460. ss << std::endl;
  461. ss << "Capture duration: " << getCaptureDurationSeconds() << " seconds" << std::endl;
  462. ss << "Capture duration (HH:MM:SS.mmmmmm): " << getCaptureDurationTimestamp() << std::endl;
  463. ss << "#Packets: " << packetCount << std::endl;
  464. ss << std::endl;
  465. // Print IP address specific statistics only if IP address was given
  466. if (ipAddress != "") {
  467. entry_ipStat e = ip_statistics[ipAddress];
  468. ss << "\n----- STATS FOR IP ADDRESS [" << ipAddress << "] -------" << std::endl;
  469. ss << std::endl << "KBytes sent: " << e.kbytes_sent << std::endl;
  470. ss << "KBytes received: " << e.kbytes_received << std::endl;
  471. ss << "Packets sent: " << e.pkts_sent << std::endl;
  472. ss << "Packets received: " << e.pkts_received << "\n\n";
  473. ip_stats is = getStatsForIP(ipAddress);
  474. ss << "Bandwidth IN: " << is.bandwidthKBitsIn << " kbit/s" << std::endl;
  475. ss << "Bandwidth OUT: " << is.bandwidthKBitsOut << " kbit/s" << std::endl;
  476. ss << "Packets per second IN: " << is.packetPerSecondIn << std::endl;
  477. ss << "Packets per second OUT: " << is.packetPerSecondOut << std::endl;
  478. ss << "Avg Packet Size Sent: " << is.AvgPacketSizeSent << " kbytes" << std::endl;
  479. ss << "Avg Packet Size Received: " << is.AvgPacketSizeRecv << " kbytes" << std::endl;
  480. }
  481. std::cout << ss.str();
  482. }
  483. /**
  484. * Derives general PCAP file statistics from the collected statistical data and
  485. * writes all data into a SQLite database, located at database_path.
  486. * @param database_path The path of the SQLite database file ending with .sqlite3.
  487. */
  488. void statistics::writeToDatabase(std::string database_path) {
  489. // Generate general file statistics
  490. float duration = getCaptureDurationSeconds();
  491. long sumPacketsSent = 0, senderCountIP = 0;
  492. float sumBandwidthIn = 0.0, sumBandwidthOut = 0.0;
  493. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  494. sumPacketsSent += i->second.pkts_sent;
  495. // Consumed bandwith (bytes) for sending packets
  496. sumBandwidthIn += (i->second.kbytes_received / duration);
  497. sumBandwidthOut += (i->second.kbytes_sent / duration);
  498. senderCountIP++;
  499. }
  500. float avgPacketRate = (packetCount / duration);
  501. long avgPacketSize = getAvgPacketSize();
  502. if(senderCountIP>0) {
  503. long avgPacketsSentPerHost = (sumPacketsSent / senderCountIP);
  504. float avgBandwidthInKBits = (sumBandwidthIn / senderCountIP) * 8;
  505. float avgBandwidthOutInKBits = (sumBandwidthOut / senderCountIP) * 8;
  506. // Create database and write information
  507. statistics_db db(database_path);
  508. db.writeStatisticsFile(packetCount, getCaptureDurationSeconds(),
  509. getFormattedTimestamp(timestamp_firstPacket.seconds(), timestamp_firstPacket.microseconds()),
  510. getFormattedTimestamp(timestamp_lastPacket.seconds(), timestamp_lastPacket.microseconds()),
  511. avgPacketRate, avgPacketSize, avgPacketsSentPerHost, avgBandwidthInKBits,
  512. avgBandwidthOutInKBits);
  513. db.writeStatisticsIP(ip_statistics);
  514. db.writeStatisticsTTL(ttl_distribution);
  515. db.writeStatisticsIpMac(ip_mac_mapping);
  516. db.writeStatisticsPorts(ip_ports);
  517. db.writeStatisticsProtocols(protocol_distribution);
  518. db.writeStatisticsMSS(mss_distribution);
  519. db.writeStatisticsToS(tos_distribution);
  520. db.writeStatisticsWin(win_distribution);
  521. db.writeStatisticsConv(conv_statistics);
  522. db.writeStatisticsInterval(interval_statistics);
  523. }
  524. else {
  525. // Tinslib failed to recognize the types of the packets in the input PCAP
  526. std::cout<<"ERROR: Statistics could not be collected from the input PCAP!"<<"\n";
  527. return;
  528. }
  529. }