Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to turn protocol number to name with python?

the protocol like tcp and udp is all represented by a number.

import socket
socket.getprotocobyname('tcp') 

the above code will return 6.

How I can get the protocol name if I know the protocol number?

like image 379
Kramer Li Avatar asked May 03 '16 13:05

Kramer Li


1 Answers

I'm going to say there is almost definitely a better way then this, but all the protocol names (and values) are stored as constants prefixed by "IPPROTO_" so you can create a lookup table by iterating over the values in the module:

import socket
prefix = "IPPROTO_"
table = {num:name[len(prefix):] 
          for name,num in vars(socket).items()
            if name.startswith(prefix)}

assert table[6] == 'TCP'
assert table[0x11] == 'UDP'
print(len(table)) # in python 3.10.0 this has 30 entries
from pprint import pprint
pprint(table) # if you want to see what is available to you
like image 52
Tadhg McDonald-Jensen Avatar answered Oct 19 '22 21:10

Tadhg McDonald-Jensen