Implementing a TCP traceroute

Asked

Viewed 177 times

0

I’m trying to understand the code below (found on the Internet):

#!/usr/bin/python3

from scapy.all import *

target = input("Informe um alvo: ")
destport = input("Porta de destino: ")

port = int(destport)

ans,unans=sr(IP(dst=target,ttl=(1,30))/TCP(dport=port,flags="S"))
ans.summary(lambda s,r: r.sprintf("%IP.src%\t{ICMP:%ICMP.type%}\t{TCP:%TCP.flags%}"))

I can’t understand the last line at all:

ans.summary(lambda s,r: r.sprintf("%IP.src%\t{ICMP:%ICMP.type%}\t{TCP:%TCP.flags%}"))

Could someone please explain to me in detail the last line of the program? Why use sprintf instead of print? I found it super confusing...

1 answer

0


ans, unans = sr(IP(dst=target, ttl=(1, 30)) / TCP(dport = port, flags = "S"))

According to the documentation, the function sr is used for sending packages, the result is a tuple with the unanswered packages and responses, and the variables are assigned ans and unans respectively.

dst is used to define the destination of the packages, ttl defines the lifetime of the package, each operating system has a different standard, for example, on Linux may be 64, in Windows is 128. In the code the ttl will be between 1 until 30. Finally, the door is defined and flag indicating SYN.

ans.summary(lambda s,r: r.sprintf("%IP.src%\t{ICMP:%ICMP.type%}\t{TCP:%TCP.flags%}"))

The variable ans contains the packages and responses resulting from the function sr, the method summary is to show a summary of each package, lambda is a Python keyword indicating an anonymous one-line function, s and r are the arguments of this function (in that question there is more information on the subject). Another way to do this would be like this:

for s, r in ans:
  print ("{} \t {} \t {}".format(r.scr, r[ICMP].type, r[TCP].flags))

Note: I didn’t test the code above!

sprintf is a function of Scapy in order to format the string with the values of the package fields, the format can include directives that start and end with %, for example: IP.src, ICMP.type, TCP.flags. At this link you can see the implementation.

For more information see the documentation.

  • 1

    thank you. The system only lets me release the reconpensa in 6 hours... As soon as available, I pass you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.