python原始套接字编程示例分享

下面开始构造http数据包,

ip层和tcp层使用python的impacket库,http内容自行填写。

代码如下:

#!/usr/bin/env python#——————————————————————————-# name: raw_http.py# purpose: construct a raw http get packet## author: yangjun## created: 08/02/2014# copyright: (c) yangjun 2014# licence: #——————————————————————————-import sysimport socketfrom impacket import impactdecoder, impactpacketdef main(): if len(sys.argv) < 3: print "use: %s " % sys.argv[0] print "use: %s " % sys.argv[0] sys.exit(1) elif len(sys.argv) == 3: src = sys.argv[1] dst = sys.argv[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(80) tcp.set_th_seq(1) tcp.set_th_ack(1) tcp.set_th_flags(0x18) tcp.set_th_win(64) tcp.contains( impactpacket.data("get /att/diylife/41264/528 http/1.1\r\nhost: 192.168.111.1\r\naccept-encoding: identity\r\n\r\n")) 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 -1if __name__ == ‘__main__’: main()

运行后抓包如下:

发表评论