tags:

views:

374

answers:

5

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

+2  A: 

Python's socket module will do that:

>>> import socket
>>> socket.getservbyport(80)
'http'
>>> socket.getservbyport(21)
'ftp'
>>> socket.getservbyport(53, 'udp')
'domain'
Jon-Eric
I added one more example because, even if you provide the link to the documentation, it will go mostly unnoticed; hope you don't mind. Cheers +1 :)
ΤΖΩΤΖΙΟΥ
+1  A: 

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'
Beau
+2  A: 

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'
Ben Blank
it's a strange dictionary (scapy.dadict.DADict object) and it doesn't have .iteritems() method
Emilio
Okay. I just took a look at the DADict code and altered my solution.
Ben Blank
A: 

If you are using unix or linux there is a file /etc/services which contains this mapping.

Alex Brown
A: 

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
Emilio