If you are interested in sniffing packets on your local network, this recipe can be used as the starting point. Remember that you may not be able to sniff packets other than what is destined to your machine, as decent network switches will only forward traffic that is designated to your machine.
You need to install the pylibpcap
library (Version 0.6.4 or greater) for this recipe to work. It's available at SourceForge (http://sourceforge.net/projects/pylibpcap/).
You also need to install the construct
library, which can be installed from PyPI via pip
or easy_install
, as shown in the following command:
$ easy_install construct
We can supply command-line arguments, for example, the network interface name and TCP port number, for sniffing.
Listing 9.1 gives the code for sniffing packets on your network, as follows:
#!/usr/bin/env python # Python Network Programming Cookbook -- Chapter - 9 # This program is optimized for Python 2.6. #...