raw soket

本文将详细介绍如何在Linux环境下利用RawSocket进行TCP包抓取,包括解析IP头部、获取源/目标端口和数据包内容等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值