This article mainly introduces Python in the use of raw sockets for network programming examples, the use of Sock_raw to accept and send packets can avoid the limitations of the network protocol, the need for friends can refer to the
In the experiment, we need to construct a separate HTTP data message, and use Sock_stream to send the packet, which requires a complete TCP interaction.
Therefore, you want to use the original socket programming, directly constructs the packet, and sends in the IP layer, namely uses the Sock_raw to carry on the data to send.
The advantage of using Sock_raw is that you can make a complete change to the packet, you can process all the packets on the IP layer, modify the fields without being restricted by UDP and TCP.
The following starts to construct the HTTP packet,
The IP layer and the TCP layer use the Python impacket Library, and the HTTP content is filled out by itself.
?
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 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 |
#!/usr/bin/env python #------------------------------------------------- ------------------------------# Name:raw_http.py # purpose:construct a raw HTTP GET packet # # Author:yangjun # # Crea ted:08/02/2014 # Copyright: (c) Yangjun 2014 # Licence: <your licence> #------------------------------------------ ------------------------------------- Import SYS import socket from impacket import Impactdecoder, Impactpacket &N Bsp def main (): If Len (SYS.ARGV) < 3:print "Use:%s <src ip> <dst ip>"% sys.argv[0] print "use:%s SRC ip> <dst ip> <cnt> "% sys.argv[0] sys.exit (1) elif len (sys.argv) = = 3:SRC = sys.argv[1] DST = Sys.arg V[2] cnt = 1 elif len (sys.argv) ==4:src = sys.argv[1] DST = sys.argv[2] cnt = sys.argv[3] else:print "Input error!" sys. Exit (1) #print src, DST IP = Impactpacket.ip () ip.set_ip_src (SRC) ip.set_ip_dst (DST) # Create a new ICMP packet of Type ECHO. ICMP = ImpactpackeT.ICMP () TCP = Impactpacket.tcp () tcp.set_th_sport (55968) tcp.set_th_dport (+) tcp.set_th_seq (1) tcp.set_th_ack (1) Tcp.set_th_flags (0x18) Tcp.set_th_win () Tcp.contains (Impactpacket.data ("get/att/diylife/41264/528 HTTP/ 1.1rnhost:192.168.111.1rnaccept-encoding:identityrnrn ")) Ip.contains (TCP) # Open a raw socket. Special permissions are usually required. s = socket.socket (socket.af_inet, socket. SOCK_RAW, Socket. IPPROTO_TCP) s.setsockopt (socket. IPPROTO_IP, Socket. IP_HDRINCL, 1) seq_id = 0 while CNT >= 1: # Calculate its checksum. seq_id = seq_id + 1 tcp.set_th_seq (seq_id) tcp.calculate_checksum () Send it to the target host. S.sendto (Ip.get_packet (), (dst,80)) cnt= cnt-1 if __name__ = = ' __main__ ': Main () |