注意事项 :
1.仅限linux/uninx 使用
2.不需要任何第三方库,仅用标准库
3.格式为公开格式,可以whireshark 直接打开
代码如下:
import time,struct
class Pcap:
def __init__(self, filename, link_type=1):
self.pcap_file = open(filename, 'wb')
self.pcap_file.write(struct.pack('@ I H H i I I I', 0xa1b2c3d4, 2, 4, 0, 0, 65535, link_type))
def write(self, data):
ts_sec, ts_usec = map(int, str(time.time()).split('.'))
length = len(data)
self.pcap_file.write(struct.pack('@ I I I I', ts_sec, ts_usec, length, length))
self.pcap_file.write(data)
def close(self):
self.pcap_file.close()
def main():
start_time=time.time()
pcap = Pcap('capture.pcap')
conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
while True:
raw_data, addr = conn.recvfrom(65535)
pcap.write(raw_data)
if time.time()-start_time()>10:break
pcap.close()
|