-
Notifications
You must be signed in to change notification settings - Fork 1
/
sniffer.py
63 lines (63 loc) · 1.95 KB
/
sniffer.py
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
#!/usr/bin/env python
import socket
import sys
import time
from struct import *
from flask import render_template,Flask,Blueprint
captureData=Blueprint('capture',__name__)
app=Flask(__name__)
@captureData.route('/capture/')
def capture():
#sv.saveData()
try:
s=socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_TCP)
f=open("Data.csv","w")
startTime=time.time()+30*1
except(socket.error,msg):
print("socket could not be created. Error code: {} and message: {} ".format((msg[0]),(msg[1])))
sys.exit()
while True:
packet=s.recvfrom(65565)
packet=packet[0]
ip_header=packet[:20]
iph=unpack('!BBHHHBBH4s4s',ip_header)
version_ihl=iph[0]
version=version_ihl >> 4
ihl=version_ihl & 0xF
iph_length=ihl*4
ttl=iph[5]
protocol=iph[6]
s_addr=socket.inet_ntoa(iph[8]);
d_addr=socket.inet_ntoa(iph[9]);
print("Version: {} IP Header Length: {} TTL: {} Protocol: {} \nSource Address: {} Dest. Address: {}".format(version,ihl,ttl,protocol,s_addr,d_addr))
#writing IP Address to a file
#f.write(str(s_addr)+",")
f.write(str(ihl)+",")
f.write(str(ttl)+",")
f.write(str(protocol)+",")
f.write(str(s_addr)+",")
f.write(str(d_addr)+",")
tcp_header=packet[iph_length:iph_length+20]
tcph=unpack('!HHLLBBHHH',tcp_header)
source_port=tcph[0]
dest_port=tcph[1]
sequence=tcph[2]
acknowledgement=tcph[3]
doff_reserved=tcph[4]
tcph_length=doff_reserved >> 4
print("Source Port: {} Dest Port: {} Sequence: {} Acknowledge: {} TCP Header Length: {}".format(source_port,dest_port,sequence,acknowledgement,tcph_length))
#Writing sorce and Dest port
f.write(str(source_port)+",")
f.write(str(dest_port)+",")
f.write(str(sequence)+",")
f.write(str(acknowledgement)+",")
f.write(str(tcph_length))
h_size=iph_length+tcph_length*4
data_size=len(packet)-h_size
data=packet[h_size:]
print("Data: {}\n".format(data))
if(time.time()>startTime):
break
f.write("\n")
#f.write(str(data))
return render_template('HomePage.html')