View difference between Paste ID: MQSi9RRe and Wzjp7KcG
SHOW: | | - or go back to the newest paste.
1
import socket, struct, os, array
2
from scapy.all import ETH_P_ALL
3
from scapy.all import select
4
from scapy.all import MTU
5
6-
#Author: askldjd
6+
7-
#See http://wp.me/pDfjR-rQ
7+
8
    def __init__(self, interface_name, on_ip_incoming, on_ip_outgoing):
9
10
        self.interface_name = interface_name
11
        self.on_ip_incoming = on_ip_incoming
12
        self.on_ip_outgoing = on_ip_outgoing
13
        
14
        # The raw in (listen) socket is a L2 raw socket that listens 
15
        # for all packets going through a specific interface.
16
        self.ins = socket.socket(
17
            socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL))
18
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
19
        self.ins.bind((self.interface_name, ETH_P_ALL))
20
        
21
    def __process_ipframe(self, pkt_type, ip_header, payload):
22
    
23
        # Extract the 20 bytes IP header, ignoring the IP options
24
        fields = struct.unpack("!BBHHHBBHII", ip_header)
25
        
26
        dummy_hdrlen = fields[0] & 0xf    
27
        iplen = fields[2]
28
29
        ip_src = payload[12:16]
30
        ip_dst = payload[16:20]
31
        ip_frame = payload[0:iplen]
32
33
        if pkt_type == socket.PACKET_OUTGOING:
34
            if self.on_ip_outgoing is not None:
35
                self.on_ip_outgoing(ip_src, ip_dst, ip_frame)
36
                
37
        else:
38
            if self.on_ip_incoming is not None:
39
                self.on_ip_incoming(ip_src, ip_dst, ip_frame)
40
                           
41
    def recv(self):
42
        while True:
43
        
44
            pkt, sa_ll = self.ins.recvfrom(MTU)
45
            
46
            if type == socket.PACKET_OUTGOING and self.on_ip_outgoing is None:
47
                continue
48
            elif self.on_ip_outgoing is None:
49
                continue
50
            
51
            if len(pkt) <= 0:
52
                break
53
                
54
            eth_header = struct.unpack("!6s6sH", pkt[0:14])
55
            
56
            dummy_eth_protocol = socket.ntohs(eth_header[2])
57
            
58
            if eth_header[2] != 0x800 :
59
                continue
60
                
61
            ip_header = pkt[14:34]
62
            payload = pkt[14:]      
63
64
            self.__process_ipframe(sa_ll[2], ip_header, payload)
65
66
#Example code to use IPSniff
67
def test_incoming_callback(src, dst, frame):
68
	pass
69
    #print("incoming - src=%s, dst=%s, frame len = %d" 
70
    #    %(socket.inet_ntoa(src), socket.inet_ntoa(dst), len(frame)))
71
72
def test_outgoing_callback(src, dst, frame):
73
	pass
74
    #print("outgoing - src=%s, dst=%s, frame len = %d" 
75
    #    %(socket.inet_ntoa(src), socket.inet_ntoa(dst), len(frame)))    
76
77
ip_sniff = IPSniff('eth0', test_incoming_callback, test_outgoing_callback)
78
ip_sniff.recv()