-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathport.py
More file actions
145 lines (123 loc) · 4.64 KB
/
Copy pathport.py
File metadata and controls
145 lines (123 loc) · 4.64 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import sys
import threading
import time
import json
from scapy.all import *
import requests
from flask import Flask, jsonify, request
import numpy as np
from flask_cors import CORS
app = Flask(__name__)
SERVER_URL = "http://localhost:5011/packet"
CORS(app)
#global vars we need
previous_times = []
icmp_requests = {}
HTTPnum = 0
HTTPSnum = 0
noHTTPnum = 0
packet_counter = 0
packet_data = []
jit = ""
rtt = ""
#this function sends packets to api for the packet sniff
def send_packet_to_server(log_entry):
try:
requests.post(SERVER_URL, json={"packet": log_entry})
except Exception:
return
#this function calculates jitter time - DOESNT WORK ALL THE TIME
def calculate_jitter(packet_time):
global previous_times
if previous_times:
jitter_values = [abs(packet_time - pt) for pt in previous_times]
avg_jitter = sum(jitter_values) / len(jitter_values)
previous_times.append(packet_time)
if len(previous_times) > 5: # Limit stored times to avoid memory issues
previous_times.pop(0)
return f"Jitter: {avg_jitter:.2f} ms"
previous_times.append(packet_time)
return "Error calculating jitter"
#function that handles packets
def handle_packet(packet):
global icmp_requests, HTTPnum, HTTPSnum, noHTTPnum, packet_counter, previous_time, jit, rtt
if packet_counter >= 50:
return #exit cond
sniff_entry = "" #resets for each run
if packet.haslayer(IP):
src_ip = packet[IP].src
dst_ip = packet[IP].dst
log_entry = ""
if packet.haslayer(TCP):
src_port = packet[TCP].sport
dst_port = packet[TCP].dport
log_entry = f"TCP CONNECTION: {src_ip}:{src_port} -> {dst_ip}:{dst_port}"
if dst_port == 80: #port 80 is HTTP
HTTPnum += 1
sniff_entry += " [HTTP]"
elif dst_port == 443: #port 443 is HTTPS
HTTPSnum += 1
sniff_entry += " [HTTPS - Encrypted]"
else:
noHTTPnum += 1 #LOCAL
sniff_entry += " [Not HTTP/HTTPS]"
if packet.haslayer(Raw) and dst_port == 80: #for getting headers
payload = packet[Raw].load.decode(errors="ignore")
if "HTTP" in payload:
log_entry += f" | HTTP Headers: {payload[:200]}"
elif packet.haslayer(UDP): #irrelevant for local tests
src_port = packet[UDP].sport
dst_port = packet[UDP].dport
log_entry = f"UDP PACKET: {src_ip}:{src_port} -> {dst_ip}:{dst_port}"
elif packet.haslayer(ICMP):
icmp_type = packet[ICMP].type
log_entry = f"ICMP PACKET: {src_ip} -> {dst_ip} (ICMP Type {icmp_type})"
if icmp_type == 8: # Echo Request
icmp_requests[src_ip] = time.time()
elif icmp_type == 0 and src_ip in icmp_requests: # Echo Reply
rtt_value = (time.time() - icmp_requests[src_ip]) * 1000
del icmp_requests[src_ip]
rtt = f"RTT: {rtt_value:.2f} ms"
jit = calculate_jitter(time.time() * 1000)
print(f"{jit}")
sniff_entry += f" {jit} | {rtt}"
if log_entry:
send_packet_to_server(log_entry)
#logging for debugging
print(f"Packets Captured: {packet_counter + 1}/50")
print(f"HTTP: {HTTPnum}, HTTPS: {HTTPSnum}, Local: {noHTTPnum}")
print(sniff_entry)
print("-" * 40)
packet_counter += 1
if packet_counter >= 50: #dump data after 15 packets
packet_data.append({
"HTTP packets": HTTPnum,
"HTTPS packets": HTTPSnum,
"Local packets": noHTTPnum,
"Average jitter": jit,
"RTT": rtt
})
with open("packet_data.json", "w") as json_file: #write to json file
json.dump(packet_data, json_file, indent=4)
json_file.flush()
print("Packet data written to packet_data.json")
sys.exit(0) # quit prog
def main(interface):
print(f"Starting packet sniffer on interface: {interface}")
try:
sniff(iface=interface, prn=handle_packet, store=0)
except KeyboardInterrupt:
print("\nSniffing stopped.")
sys.exit(0)
except PermissionError:
print("Permission denied! Try running with sudo.")
sys.exit(1)
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python script.py <network_interface>")
sys.exit(1)
interface = sys.argv[1]
main(interface)