Skip to content Skip to sidebar Skip to footer

Python-scapy: How To Translate Port Numbers To Service Names?

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_SERV

Solution 1:

Python's socket module will do that:

>>>import socket>>>socket.getservbyport(80)
'http'
>>>socket.getservbyport(21)
'ftp'
>>>socket.getservbyport(53, 'udp')
'domain'

Solution 2:

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'

Solution 3:

This may work for you (filtering the dictionary based on the value):

>>> [k for k, v in TCP_SERVICES.iteritems() ifv== 80][0]
'www'

Solution 4:

Solution 5:

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 

Post a Comment for "Python-scapy: How To Translate Port Numbers To Service Names?"