raw soket

linux下raw socket抓取tcp包

import socket
import struct
import thread
import threading
import time
import os

def decodeIpHeader(packet):
        mapRet = {}
        mapRet["version"] = (int(ord(packet[0])) & 0xF0)>>4
        mapRet["headerLen"] = (int(ord(packet[0])) & 0x0F)<<2
        mapRet["serviceType"] = hex(int(ord(packet[1])))
        mapRet["totalLen"] = (int(ord(packet[2])<<8))+(int(ord(packet[3])))
        mapRet["identification"] = (int( ord(packet[4])>>8 )) + (int( ord(packet[5])))
        mapRet["id"] = int(ord(packet[6]) & 0xE0)>>5
        mapRet["fragOff"] = int(ord(packet[6]) & 0x1F)<<8 + int(ord(packet[7]))
        mapRet["ttl"] = int(ord(packet[8]))
        mapRet["protocol"] = int(ord(packet[9]))
        mapRet["checkSum"] = int(ord(packet[10])<<8)+int(ord(packet[11]))
        mapRet["srcaddr"] = "%d.%d.%d.%d" % (int(ord(packet[12])),int(ord(packet[13])),int(ord(packet[14])), int(ord(packet[15])))
        mapRet["dstaddr"] = "%d.%d.%d.%d" % (int(ord(packet[16])),int(ord(packet[17])),int(ord(packet[18])), int(ord(packet[19])))
	mapRet["srcport"] = int(ord(packet[20]))
	mapRet["dstport"] = int(ord(packet[21]))
	mapRet["tcplength"] = (int(ord(packet[32]))&0xF0)>>2
        return mapRet 		

def get_packet():
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)

    while True:
        buf = s.recvfrom(65565)
        data_len = len(buf[0])
	mapRet = decodeIpHeader(buf[0][:])
        port = struct.unpack('HH', buf[0][20:24])
       	length = "%d"%struct.unpack('>H', buf[0][2:4]) 
        src_ip = "%d.%d.%d.%d"%struct.unpack('BBBB', buf[0][12:16])
        dest_ip ="%d.%d.%d.%d"%struct.unpack('BBBB', buf[0][16:20])
        src_port = socket.htons(port[0])
        dest_port = socket.htons(port[1])
	datalen = mapRet['totalLen']-mapRet["headerLen"]-mapRet["tcplength"]
	if datalen> 0:
		data = "%s"%(struct.unpack("%ds"%datalen, buf[0][(mapRet["headerLen"]+mapRet["tcplength"]):mapRet['totalLen']])) 
		print data
		raw_input()
        key="%s:%d=>%s:%d"%(src_ip,src_port,dest_ip,dest_port)
	print "--------------------------------------"
	print key
	print 'totallength:',mapRet['totalLen']
	print 'iplength:',mapRet["headerLen"]
	print 'tcplength:',mapRet['tcplength']
	time.sleep(1)
get_packet()


你可能感兴趣的:(raw soket)