Advertisement
kator

statystyki pseciowe

Mar 21st, 2019
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.10 KB | None | 0 0
  1. /*
  2.  * Copyright (C) 2019 Michal Kalewski <mkalewski at cs.put.poznan.pl>
  3.  *
  4.  * Compilation:  gcc -Wall ./pcapsniff.c -o ./pcapsniff -lpcap
  5.  * Usage:        ./pcapsniff INTERFACE
  6.  * NOTE:         This program requires root privileges.
  7.  *
  8.  * Bug reports:  https://gitlab.cs.put.poznan.pl/mkalewski/ps-2019/issues
  9.  *
  10.  */
  11.  
  12. #include <pcap.h>
  13. #include <signal.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <linux/if_ether.h>
  17. #include <linux/ip.h>
  18. #include <linux/types.h>
  19.  
  20. char* errbuf;
  21. pcap_t* handle;
  22.  
  23. struct stats {
  24.     long arp;
  25.     long ip;
  26.     long ip_udp;
  27.     long ip_tcp;
  28.     long inne;
  29. };
  30.  
  31. struct stats staty;
  32. void resetStaty(){
  33.   staty.arp = 0;
  34.   staty.ip = 0;
  35.   staty.ip_udp = 0;
  36.   staty.ip_tcp = 0;
  37.   staty.inne = 0;
  38. }
  39.  
  40. void printStats() {
  41.     printf("Statystyki: \n");
  42.     printf("\tArp:\t%d\n", staty.arp);
  43.     printf("\tIP:\t%d\n", staty.ip);
  44.     printf("\t\tUDP:\t%d\n", staty.ip_udp);
  45.     printf("\t\tTCP:\t%d\n", staty.ip_tcp);
  46.     printf("\tInne:\t%d\n", staty.inne);
  47. }
  48.  
  49. void cleanup() {
  50.   pcap_close(handle);
  51.   free(errbuf);
  52. }
  53.  
  54. void stop(int signo) {
  55.     // print stats
  56.   exit(EXIT_SUCCESS);
  57. }
  58.  
  59. void trap(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes) {
  60.   struct ethhdr *ramka = (struct ethhdr*) bytes;
  61.   int etherType = ntohs(ramka-> h_proto);
  62.  
  63.   if(ETH_P_ARP == etherType) {
  64.     staty.arp++;
  65.   } else if (ETH_P_IP == etherType ){
  66.     staty.ip++;
  67.     struct iphdr *ipRamka = (struct iphdr*) (sizeof(struct ethhdr)+ ramka);
  68.     if(17 == ipRamka->protocol){
  69.       staty.ip_udp++;
  70.     } else if(6 == ipRamka->protocol){
  71.       staty.ip_tcp++;
  72.     }
  73.     free(ipRamka);
  74.   } else {
  75.     staty.inne++;
  76.   }
  77.   free(ramka);
  78. //   struct ethhdr = ((struct ethhdr*) bytes);
  79.   // ETH_P_ARP
  80.   // ETH_P_IP
  81.   printf("[%dB of %dB]\n", h->caplen, h->len);
  82. }
  83.  
  84. int main(int argc, char** argv) {
  85.   atexit(cleanup);
  86.   signal(SIGINT, stop);
  87.   errbuf = malloc(PCAP_ERRBUF_SIZE);
  88.   handle = pcap_create(argv[1], errbuf);
  89.   pcap_set_promisc(handle, 1);
  90.   pcap_set_snaplen(handle, 65535);
  91.   pcap_activate(handle);
  92.   pcap_loop(handle, -1, trap, NULL);
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement