forked from B-and-w-sec/Python-Tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sniffer.py
72 lines (48 loc) · 1.88 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
64
65
66
67
68
69
70
#!/usr/bin/python
import socket
import struct
from ctypes import *
class IPHeader(Structure):
_fields_ = [
("ihl", c_ubyte, 4),
("version", c_ubyte, 4),
("tos", c_ubyte),
("len", c_ushort),
("id", c_ushort),
("offset", c_ushort),
("ttl", c_ubyte),
("protocol_num", c_ubyte),
("sum", c_ushort),
("src", c_uint32),
("dst", c_uint32)
]
def __new__(self,data=None):
## lets make a structure of our packets captured
return self.from_buffer_copy(data)
def __init__(self,data=None):
self.source_ip = socket.inet_ntoa(struct.pack("@I",self.src))
self.destination_ip = socket.inet_ntoa(struct.pack("@I",self.dst))
self.protocols = {1:"ICMP",6:"TCP",17:"UDP"}
try:
self.protocol = self.protocols[self.protocol_num]
except:
self.protocol = str(self.protocol_num)
def conn():
sock = socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_TCP)
sock.bind(("0.0.0.0",0))
sock.setsockopt(socket.IPPROTO_IP,socket.IP_HDRINCL,1)
return sock
def main():
sniffer = conn()
print "Sniffer Started: "
# Get the raw Packets
while True:
try:
raw_pack = sniffer.recvfrom(65535)[0]
ip_header = IPHeader(raw_pack[0:20])
if(ip_header.protocol == "TCP"):
print "Protocol: " + ip_header.protocol + " Source: " + ip_header.source_ip + " Destination: " + ip_header.destination_ip
except KeyboardInterrupt:
print "Exiting...."
exit(0)
main()