How to convert protocol number for name using python?

a protocol such as tcp and udp is represented by a number.

import socket
socket.getprotocobyname('tcp') 

the above code will return 6.

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

+4
source share
2 answers

I'm going to say that there is almost certainly a better way than this, but all protocol names (and values) are stored as constants with a prefix "IPPROTO", so you can create a lookup table by iterating the values ​​into a module:

import socket

table = {num:name[8:] for name,num in vars(socket).items() if name.startswith("IPPROTO")}

>>> table[6]
'TCP'
+3
source

The Python socket module will do this:

import socket
socket.getservbyport(80)

Results in

>>> import socket
>>> socket.getservbyport(6)
'zip'
>>> socket.getservbyport(80)
'http'

socket.getservbyname(servicename[, protocolname]) socket.getservbyport(port[, protocolname]). , , "tcp" "udp", .

+2

All Articles