Pankaj
Pankaj

Reputation: 33

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

import pyshark

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

pkt[1].ip.proto 

output: 17

I would like to print 'UDP' instead of '17'

Upvotes: 2

Views: 1143

Answers (1)

Ross Jacobs
Ross Jacobs

Reputation: 3186

A list of protocol numbers can be found here: https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml

Conversion

Essentially we want to convert the protocol number to the name using python's builtin socket library like this question.

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)

This should yield UDP, provided the specified packet has a UDP layer.

Verifying this solution

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

With the output of the above code snippet, we see that these are the protocol numbers known to socket as of the writing of this answer:

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

Upvotes: 3

Related Questions