7

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?

2
  • 3
    See bugs.python.org/issue24809 Commented May 3, 2016 at 13:23
  • Python 2 or Python 3? Commented May 3, 2016 at 13:25

2 Answers 2

13

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
Sign up to request clarification or add additional context in comments.

3 Comments

While it gives protocols up to 6 that's tcp (except 3 and 5), it is unable to give beyond that. Say 11 is for UDP for which the above script gives a key-error.
@RatDon table[17] == 'UDP' and according to microsoft's protocol numbers UDP is associated with 17. Not sure where 11 is coming from but I frankly don't know much about this area, sorry I can't be more help to you.
sorry, My mistake, I took the hexadecimel number which is '11'. But still 132 is not available which is for SCTP. Yeah I agree. few fields are available but not all. Anyway, Thanks.
-3

Python's socket module will do that:

import socket
socket.getservbyport(80)

Results in

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

As the documentation mentioned for socket.getservbyname(servicename[, protocolname]) and socket.getservbyport(port[, protocolname]). The second optional protocol name, if given, should be 'tcp' or 'udp', otherwise any protocol will match.

3 Comments

is socket.getservbyport(6) "tcp" ?
nope, it's 'zip', I don't think this is the right thing
@salomonderossi, are you able to use getservbyport in any way to associate 6 with tcp? The OP is asking "given 6 how can I get back 'tcp'" which you do not do in your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.