1+ import socket , select , struct , time
2+ from get_hw import get_hw , u_to_str
3+
4+ class RawPacket ():
5+ def __init__ (self , data ):
6+ self .dest = ""
7+ self .src = ""
8+ self .type = ""
9+ self .data = ""
10+ self .success = False
11+ try :
12+ self .dest , self .src , self .type = data [0 :6 ], data [6 :12 ], data [12 :14 ]
13+ self .data = data [14 :]
14+ self .success = True
15+ except :
16+ self .success = False
17+
18+ def __repr__ (self ):
19+ return "" .join ([u_to_str (self .src ), " == 0x" , u_to_str (self .type , separator = "" ), " => " , u_to_str (self .dest ), " - " , "OK" if self .success else "FAILED" ])
20+
21+ def __str__ (self ):
22+ return "" .join ([self .__repr__ (), ":\n " , self .data ])
23+
24+ class RawSocket (object ):
25+ BROADCAST = "\xff \xff \xff \xff \xff \xff "
26+ def __init__ (self , interface , protocol , sock = None , no_recv_protocol = False ):
27+ if not 0x0000 < protocol < 0xFFFF :
28+ raise ValueError ("Protocol has to be in the range 0 to 65535" )
29+ self .protocol = socket .htons (protocol )
30+ self .ethertype = self .protocol_to_ethertype (protocol )
31+ self .interface = interface
32+ self .mac = get_hw (self .interface )
33+ if no_recv_protocol :
34+ self .sock = self .sock_create (self .interface , 0 , sock )
35+ else :
36+ self .sock = self .sock_create (self .interface , self .protocol , sock )
37+
38+ @staticmethod
39+ def sock_create (interface , protocol , sock = None ):
40+ if sock is None :
41+ sock = socket .socket (socket .AF_PACKET , socket .SOCK_RAW , protocol )
42+ sock .bind ((interface , 0 ))
43+ return sock
44+
45+ @staticmethod
46+ def protocol_to_ethertype (protocol ):
47+ return chr ((protocol & 0xFF00 ) >> 8 ) + chr (protocol & 0x00FF )
48+
49+ def send (self , msg , dest = None , ethertype = None ):
50+ if ethertype is None : ethertype = self .ethertype
51+ if dest is None : dest = self .BROADCAST
52+ self .sock .send (dest + self .mac + ethertype + msg )
53+
54+ def recv (self ):
55+ data = self .sock .recv (1500 )
56+ return RawPacket (data )
57+
58+ def __str__ (self ):
59+ return self .interface
60+
61+ def main ():
62+ na = NetworkAdapter ("wlp2s0" , 0xAA42 )
63+ i = 0
64+ while True :
65+ try :
66+ na .send (str (i ))
67+ time .sleep (0.1 )
68+ i += 1
69+ except :
70+ break
71+
72+ if __name__ == '__main__' :
73+ main ()
0 commit comments