如何在pyshark中打印协议名称而不是相应的数字?

How to print protocol name instead of corresponding number in pyshark?

import pyshark

pkt = pyshark.FileCapture('mypacket.pcap')

pkt[1].ip.proto 

输出: 17

我想打印 'UDP' 而不是 '17'

协议编号列表可在此处找到:https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml

转化

本质上我们想使用 python 的内置 socket 库将协议号转换为名称,例如 .

import socket
import pyshark


def proto_name_by_num(proto_num):
    for name,num in vars(socket).items():
        if name.startswith("IPPROTO") and proto_num == num:
            return name[8:]
    return "Protocol not found"

def packet_lvl4_protocol(filepath, packet_num):
    packet_capture = pyshark.FileCapture(filepath)
    pkt = packet_capture[packet_num]
    proto_num = int(pkt.ip.proto)
    proto_name = proto_name_by_num(proto_num)
    return proto_name

layer_name = packet_lvl4_protocol("mypacket.pcap", 1)
print(layer_name)

这应该会产生 UDP,前提是指定的数据包具有 UDP 层。

验证此解决方案

for i in range(257):
    proto_name = proto_name_by_num(i)
    if proto_name != "Protocol not found":
        print(i, num)

通过上面代码片段的输出,我们看到这些是 socket 在撰写此答案时已知的协议编号:

0 IP
1 ICMP
2 IGMP
3 GGP
4 IPV4
6 TCP
8 EGP
12 PUP
17 UDP
22 IDP
29 TP
36 XTP
41 IPV6
43 ROUTING
44 FRAGMENT
46 RSVP
47 GRE
50 ESP
51 AH
58 ICMPV6
59 NONE
60 DSTOPTS
63 HELLO
77 ND
80 EON
103 PIM
108 IPCOMP
132 SCTP
255 RAW
256 MAX