以下是对数据集进行源ip、目的ip提取的python3代码(如果是用python2 ,if type[0] == 8 and type[1] == 0:应改为if type==’/x08/x00’).代码原理非常简单,即用read()函数对数据集内容按字节读取,生成元组data。再按照数据报格式把所需要的源ip地址信息、目的ip地址信息、长度信息读取出来,并不断循环直到解析结束为止
pcap文件格式如下图:
import datetime
import struct
import os
import time
def ip_parse():
global timeslot
global start
global user_slots
# 修改文件路径filepath
file = open(‘C:/Users/hp/Documents/Tencent Files/2429185651/FileRecv/t0001’, ‘rb’)
data = file.read() # read函数返回读取的字节
i = 24
j = 40
k = 54
while i < len(data): # python区间左闭右开
seconds = struct.unpack('I', data[i:i + 4])[0] # seconds为由data【i:i+4】解析得到的元组的第一个元素
microseconds = float(struct.unpack('I', data[i + 4:i + 8])[0]) / 1000000 # struct.unpack(fmt,string)
# 返回一个由解包数据(string)得到的一个元组(tuple), 即使仅有一个数据也会被解包成元组。其中len(string) 必须等于
# calcsize(fmt),struct.calcsize(fmt):这个就是用来计算fmt格式所描述的结构的大小。
timestamp = seconds + microseconds
length = struct.unpack('I', data[i + 8:i + 12])[0] #24到35
type = data[j + 12:j + 14] #52到53
if type[0] == 8 and type[1] == 0: #66到73
sip = str(struct.unpack('B', data[k + 12:k + 13])[0]) + '.' + str( #源ip地址
struct.unpack('B', data[k + 13:k + 14])[0]) + \
'.' + str(struct.unpack('B', data[k + 14:k + 15])[0]) + '.' + str(
struct.unpack('B', data[k + 15:k + 16])[0])
dip = str(struct.unpack('B', data[k + 16:k + 17])[0]) + '.' + str( #目的ip地址
struct.unpack('B', data[k + 17:k + 18])[0]) + \
'.' + str(struct.unpack('B', data[k + 18:k + 19])[0]) + '.' + str(
struct.unpack('B', data[k + 19:k + 20])[0])
sip_combined = struct.unpack('B', data[k + 12:k + 13])[0] * (255 ** 3) + \
struct.unpack('B', data[k + 13:k + 14])[0] * (255 ** 2) + \
struct.unpack('B', data[k + 14:k + 15])[0] * 255 + struct.unpack('B', data[k + 15:k + 16])[0]
dip_combined = struct.unpack('B', data[k + 16:k + 17])[0] * (255 ** 3) + \
struct.unpack('B', data[k + 17:k + 18])[0] * (255 ** 2) + \
struct.unpack('B', data[k + 18:k + 19])[0] * 255 + struct.unpack('B', data[k + 19:k + 20])[0]
i = i + length + 16
j = j + length + 16
k = k + length + 16
file.close()
if name == ‘main’:
ip_parse()