Skip to content

Commit 290d6f2

Browse files
从pcap文件中提取ip层数据
1 parent a73a9d5 commit 290d6f2

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

parserip.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/usr/bin/env python
2+
#coding=utf-8
3+
#读取pcap文件,将ip层提取出来
4+
#24Byte pcap文件头
5+
#16Byte的pcap包头
6+
#14Byte的Ethernet报文
7+
#ip层
8+
import struct
9+
fpcap = open('yy.pcap','rb')
10+
ftxt = open('result.txt','w')
11+
string_data = fpcap.read()
12+
#pcap文件包头解析
13+
pcap_header = {}
14+
pcap_header['magic_number'] = string_data[0:4]
15+
pcap_header['version_major'] = string_data[4:6]
16+
pcap_header['version_minor'] = string_data[6:8]
17+
pcap_header['thiszone'] = string_data[8:12]
18+
pcap_header['sigfigs'] = string_data[12:16]
19+
pcap_header['snaplen'] = string_data[16:20]
20+
pcap_header['linktype'] = string_data[20:24]
21+
#pcap文件的数据包解析
22+
step = 0
23+
packet_num = 0
24+
packet_data = []
25+
pcap_packet_header = {}
26+
i =24
27+
while(i<len(string_data)):
28+
29+
#数据包头各个字段
30+
pcap_packet_header['GMTtime'] = string_data[i:i+4]
31+
pcap_packet_header['MicroTime'] = string_data[i+4:i+8]
32+
pcap_packet_header['caplen'] = string_data[i+8:i+12]
33+
pcap_packet_header['len'] = string_data[i+12:i+16]
34+
packet_len = struct.unpack('I',pcap_packet_header['len'])[0]
35+
#写入此包数据
36+
packet_data.append(string_data[i + 16 + 14:i + 16 + packet_len])
37+
i = i+ packet_len + 16
38+
packet_num+=1
39+
#把pacp文件里的数据包信息写入result.txt
40+
for i in range(packet_num):
41+
#再写数据部分
42+
ftxt.write(packet_data[i])

0 commit comments

Comments
 (0)