If you encounter the issue of detecting a network broadcast, this recipe is for you. We can learn how to find the information from the broadcast packets.
We can use Scapy
to sniff the packets arriving to a network interface. After each packet is captured, they can be processed by a callback function to get the useful information from it.
Listing 9.7 gives the code for scanning the broadcast of packets, as follows:
#!/usr/bin/env python # Python Network Programming Cookbook -- Chapter - 9 # This program is optimized for Python 2.7. # It may run on any other version with/without modifications. from scapy.all import * import os captured_data = dict() END_PORT = 1000 def monitor_packet(pkt): if IP in pkt: if not captured_data.has_key(pkt[IP].src): captured_data[pkt[IP].src] = [] if TCP in pkt: if pkt[TCP].sport <= END_PORT: if not str(pkt[TCP].sport) in captured_data[pkt[IP].src]: captured_data[pkt[IP].src].append(str(pkt[TCP].sport)) os.system('clear') ip_list = sorted(captured_data.keys()) for key in ip_list: ports=', '.join(captured_data[key]) if len (captured_data[key]) == 0: print '%s' % key else: print '%s (%s)' % (key, ports) if __name__ == '__main__': sniff(prn=monitor_packet, store=0)
If you run this script, you can list the broadcast traffic's source IP and ports. The following is a sample output from which the first octet of the IP is replaced:
# python 9_7_broadcast_scanning.py 10.0.2.15 XXX.194.41.129 (80) XXX.194.41.134 (80) XXX.194.41.136 (443) XXX.194.41.140 (80) XXX.194.67.147 (80) XXX.194.67.94 (443) XXX.194.67.95 (80, 443)
This recipe sniffs packets in a network using the sniff()
function of Scapy
. It has a monitor_packet()
callback function that does the postprocessing of packets. Depending on the protocol, for example, IP or TCP, it sorts the packets in a dictionary called captured_data
.
If an individual IP is not already present in the dictionary, it creates a new entry; otherwise, it updates the dictionary with the port number for that specific IP. Finally, it prints the IP addresses and ports in each line.
3.15.229.111