Saturday, November 26, 2022

Python: Count Source IP Addresses from Captured Packets And Display on a Table

I am curious how many IP addresses I visited on a given period of time and how many times did I visited each one of these IP addresses. This is what I am trying accomplish using python and scapy. 

I think having access to this data would mean a lot to cyber security analysts because they would know in summary how much a user consumes network traffic on any given period of time. For example, youtube's ip address appeared 100 times every hour  everyday would seem to be unacceptable. It would seem to be something fishy about this network activity and would therefore be flagged as a security concern.

Here is the sample output:


The program counts the IP layer and when it reaches 10, it automatically exits or end the program. I will upgrade this by adding a user graphical interface in the future.


Here is the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from scapy.all import *
from prettytable import PrettyTable
from collections import Counter
import scapy.all as scapy
from scapy.layers import http
from scapy.layers.inet import IP, TCP
srcIP = []
cnt = Counter()
x = 0
def sniffer(interface):
  scapy.sniff(iface=interface,store=False,prn=process_packet,filter='tcp')

def process_packet(packet):
   #print(packet.show())
   global srcIP, cnt, x
   
   try:
       srcIP.append(packet[IP].src)
       cnt[packet[IP].src] += 1
       x += 1
   except:
       pass
   
   if x==10:
       table = PrettyTable(['IP', 'Count'])
       for ip, count in cnt.most_common():
           table.add_row([ip, count])
       print(table)
       exit()
   
   


sniffer('Wi-Fi')


No comments:

Post a Comment