2017年5月5日 星期五

[python] dpkt 處理 pcap 檔函式庫

最近因為需要了解 Tensorflow 在進行分散式學習的過程中,權重更新的頻率,

因此想透過網路封包交換資訊的大小、頻率來摸索出分散式學習的運作機制

藉此來從系統的角度來熟悉 Parameter server 的運作機制

看過了這篇 pcap python library?

依序試過了 pycapfile, pyshark, scapy 這幾個讀pcap檔的工具

pypcapfile 則是因為官方資訊不夠完全,無法讀檔,立刻放棄

pyshark 則是因為還不夠成熟

scapy 在讀pcap檔上,因為一次把資料讀取進來的方式讓讀檔速度過慢,決定放棄

因此最後決定嘗試 dpkt 這款外部函式庫( 官方 Document 在此 )


dpkt


恰如它所說的 fast, simple packet creation / parsing, with definitions for the basic TCP/IP protocols

讀檔

讀檔的部份使用的語法是 dpkt.pcap.Reader()

f = open('test.pcap')  # 開檔
pcap = dpkt.pcap.Reader(f) # 讀檔


IPv4 or IPv6

如何知道IPv4 or IPv6 ?

透過下面的loop就可以知道版本號,如果 ip.v 回傳4,就是IPv4,若是6,則是IPv6

for buf in pcap:
     # Unpack the Ethernet frame (mac src/dst, ethertype)
     eth = dpkt.ethernet.Ethernet(buf)
     ip = eth.data
     if( ip.v == 4):
        print 'IPv4'
     elif( ip.v == 6):
        print 'IPv6'

另外,如果只是單純要取得IP資訊,也可以寫成

ip = dpkt.ip.IP(data)
ip = ether.data
ip_addr = socket.inet_ntoa(ip.src|ip.dst)


更多程式 API 的細節可以參考這份文檔:  My documentation on dpkt

網路知識補充

什麼是 socket?[4]
Sockets allow communication between two different processes on the same or different machines.
To be more precise, it's a way to talk to other computers using standard Unix file descriptors[5]. 
A file descriptor is just an integer associated with an open file and it can be a network connection, a text file, a terminal, or something else. 
而網路這邊所用的 socket 屬於Stream Sockets,並且遵守 TCP(Transmission Control Protocol) 規範

參考範例

1. dpkt Tutorial #2: Parsing a PCAP File

2. Source code for examples.print_packets

3. TCP/IP

4. What is a Socket?

5. 檔案描述符

沒有留言:

張貼留言

/* 載入prettify的autoloader */ /* 載入JQuery */