python-scapy: how to translate port numbers to service names?
Question
A TCP layer in Scapy contains source port:
>>> a[TCP].sport
80
Is there a simple way to convert port number to service name? I've seen Scapy has TCP_SERVICES
and UDP_SERVICES
to translate port number, but
print TCP_SERVICES[80] # fails
print TCP_SERVICES['80'] # fails
print TCP_SERVICES.__getitem__(80) # fails
print TCP_SERVICES['www'] # works, but it's not what i need
80
Someone know how can I map ports to services?
Thank you in advance
Solution
If this is something you need to do frequently, you can create a reverse mapping of TCP_SERVICES
:
>>> TCP_REVERSE = dict((TCP_SERVICES[k], k) for k in TCP_SERVICES.keys())
>>> TCP_REVERSE[80]
'www'
OTHER TIPS
Python's socket module will do that:
>>> import socket
>>> socket.getservbyport(80)
'http'
>>> socket.getservbyport(21)
'ftp'
>>> socket.getservbyport(53, 'udp')
'domain'
This may work for you (filtering the dictionary based on the value):
>>> [k for k, v in TCP_SERVICES.iteritems() if v == 80][0]
'www'
If you are using unix or linux there is a file /etc/services which contains this mapping.
I've found a good solution filling another dict self.MYTCP_SERVICES
for p in scapy.data.TCP_SERVICES.keys():
self.MYTCP_SERVICES[scapy.data.TCP_SERVICES[p]] = p
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow