statistics.cpp 24 KB

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