資源簡介
sniffer_get_body.py
代碼片段和文件信息
import?struct
import?socket
ip_header_fmt?=?‘!BBHHHBBH4s4s‘
tcp_header_fmt?=?‘!HHLLBBHHH‘
udp_header_fmt?=?‘!HHHH‘
IP_HEAD_LEN?=?struct.calcsize(ip_header_fmt)??#?20字節
TCP_HEADER_LEN?=?struct.calcsize(tcp_header_fmt)??#?20字節
UDP_HEAD_LEN?=?struct.calcsize(udp_header_fmt)??#?8字節
IP_MAX_LEN?=?65535
def?unpack_ip_header(buf):
????if?len(buf)?????????return
????try:
????????iph?=?struct.unpack(ip_header_fmt?buf[:IP_HEAD_LEN])
????????protocol_map?=?{1:?‘ICMP‘?6:?‘TCP‘?17:?‘UDP‘}
????????return?{
????????????‘version‘:?iph[0]?>>?4??#?高4位
????????????‘ihl‘:?(iph[0]?&?0xF)?*?4??#?低4位,每個長度單位表示4字節,最大為60字節
????????????‘tos‘:?iph[1]??#?8位
????????????‘len‘:?iph[2]??#?16位
????????????‘id‘:?iph[3]??#?16位
????????????‘offset‘:?iph[4]??#?16位
????????????‘ttl‘:?iph[5]??#?8位
????????????‘protocol‘:?protocol_map.get(iph[6]?str(iph[6]))??#?8位
????????????‘cks‘:?iph[7]??#?16位
????????????‘src‘:?iph[8]??#?32位
????????????‘dst‘:?iph[9]??#?32位
????????}
????except?Exception?as?e:
????????raise?e
def?unpack_tcp_header(buf):
????if?len(buf)?????????return
????try:
????????tcph?=?struct.unpack(tcp_header_fmt?buf[:TCP_HEADER_LEN])
????????return?{
????????????‘src‘:?tcph[0]??#?16位
????????????‘dst‘:?tcph[1]??#?16位
????????????‘seq‘:?tcph[2]??#?32位
????????????‘ack‘:?tcph[3]??#?32位
????????????‘thl‘:?(tcph[4]?>>?4)?*?4??#?高4位
????????????‘wlen‘:?tcph[6]??#?16位
????????}
????except?Exception?as?e:
????????raise?e
def?unpack_udp_header(buf):
????if?len(buf)?????????return
????try:
????????udph?=?struct.unpack(udp_header_fmt?buf[:UDP_HEAD_LEN])
????????return?{
????????????‘src‘:?udph[0]??#?16位
????????????‘dst‘:?udph[1]??#?16位
????????????‘dlen‘:?udph[2]??#?16位
????????????
評論
共有 條評論