Skip to content

Instantly share code, notes, and snippets.

@nobonobo
Created July 27, 2013 12:29
Show Gist options
  • Select an option

  • Save nobonobo/6094740 to your computer and use it in GitHub Desktop.

Select an option

Save nobonobo/6094740 to your computer and use it in GitHub Desktop.
pythonでpcapファイルを書き出すのをやってみた。意外と簡単だった。
#!/usr/bin/env python
# encoding: utf-8
import os
import time
import struct
FileHeader = struct.Struct(format="<LHHlLll")
PacketHeader = struct.Struct(format="<LLLL")
FLAGS = os.O_CREAT|os.O_APPEND|os.O_WRONLY|os.O_EXLOCK|os.O_SYNC
snaplen = 65536
def write(fname, pkt):
buff = []
fd = os.open(fname, FLAGS)
try:
if os.fstat(fd).st_size == 0:
buff.append(FileHeader.pack(0xa1b2c3d4, 2, 4, 0, 0, snaplen, 1))
length = orglen = len(pkt)
while length:
tm = time.time()
sprit = min(snaplen, length)
buff.append(PacketHeader.pack(int(tm),int(tm%1*1000000), sprit, orglen))
buff.append(pkt)
length -= sprit
return os.write(fd, b''.join(buff))
finally:
os.close(fd)
sample = (
"\x04\x0c\xce\xd5\x6c\x3a\x1c\xb1"
"\x7f\x53\x6d\x20\x08\x00\x45\x00\x00\x59\xcf\xb3\x40\x00\x2c\x06"
"\xaf\x65\x6c\xa0\xa2\x35\xc0\xa8\x00\x08\x01\xbb\xcf\x3b\x53\x07"
"\xfd\x5b\xee\x8e\x46\x45\x80\x18\x00\x35\x90\x34\x00\x00\x01\x01"
"\x08\x0a\x09\xfc\x63\xc7\x1e\x24\x9f\xeb\x15\x03\x01\x00\x20\xeb"
"\x82\xa1\x3a\x7e\x17\x2a\x05\x16\xe0\x49\x31\x5d\x53\xb6\x63\xbf"
"\x46\xf7\xe0\xd1\x6d\xc5\xda\x4b\x19\x82\xc8\x34\x4f\xa3\x1a")
if __name__=='__main__':
write('hoge.pcap', sample)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment