In the previous article I demonstrated how to add a custom function to change the formatting of the packet output in the console or do some sort of custom action with each packet. That example passed the function (a Callable) without any additional args. When the prn passed function is called (with each packet), it receives a single argument of the packet that was just sniffed.
Using nested functions to harness the power of closure, you can bind any number of arguments to the function that is executed on each packet by Scapy. In order to bind additional arguments to the prn function, we have to use nested functions (similar to a decorator). Check out this example, created to upload the scapy packet info to an API via the Python Requests module:
Scapy has a sniff
function that is great for getting packets off the wire, but there's much more to show off how great this function really is! sniff
has an argument prn
that allows you to pass a function that executes with each packet sniffed. The intended purpose of this function is to control how the packet prints out in the console allowing you to replace the default packet printing display with a format of your choice.
The prn
argument is defined as:
prn: function to apply to each packet. If something is returned, it is displayed. For instance you can use prn = lambda x: x.summary().