我的代码用于将pcap文件中的IP地址打印在CSV文件中,它可以正常工作,但问题是它只存储了pcap文件的第一个数据包。我不知道出了什么问题...
请问有人能帮我解决这个问题吗?
以下是我的代码:
以下是我的代码:
import dpkt
from dpkt.ip import IP
from dpkt.ethernet import Ethernet
import struct
import socket
import csv
def ip_to_str(address):
return socket.inet_ntoa(address)
f = open('sample.pcap', 'rb')
pcap = dpkt.pcap.Reader(f)
for ts, buf in pcap:
eth = dpkt.ethernet.Ethernet(buf)
if eth.type != dpkt.ethernet.ETH_TYPE_IP:
continue
ip = eth.data
do_not_fragment = bool(dpkt.ip.IP_DF)
more_fragments = bool(dpkt.ip.IP_MF)
fragment_offset = bool(dpkt.ip.IP_OFFMASK)
c = csv.writer(open("a.csv", "wb"))
Source = "%s" % ip_to_str(ip.src)
Destination = "%s" % ip_to_str(ip.dst)
Length = "%d" % (ip.len)
TTL = "%d" % (ip.ttl)
OFF = ip.off
TOS = ip.tos
Protocol = ip.p
data = (Source, Destination, Length, TTL, TOS, OFF, Protocol)
c.writerow(data)