import struct from ctypes import host to listen on host our ip header class ip(structure)_fields_ ("ihl"("version"("tos"("len"("id"("offset"("ttl"("protocol_num"("sum"("src"("dst"c_ubyte )c_ubyte )c_ubyte)c_ushort)c_ushort)c_ushort)c_ubyte)c_ubyte)c_ushort)c_ulong)c_ulongdef __new__(selfsocket_buffer=none)return self from_buffer_copy(socket_bufferdef __init__(selfsocket_buffer=none)map protocol constants to their names self protocol_map { :"icmp" :"tcp" :"udp"human readable ip addresses self src_address socket inet_ntoa(struct pack("< ",self src)self dst_address socket inet_ntoa(struct pack("< ",self dst)human readable protocol tryself protocol self protocol_map[self protocol_numexceptself protocol str(self protocol_numthis should look familiar from the previous example if os name ="nt"socket_protocol socket ipproto_ip elsesocket_protocol socket ipproto_icmp sniffer socket socket(socket af_inetsocket sock_rawsocket_protocolsniffer bind((host )sniffer setsockopt(socket ipproto_ipsocket ip_hdrincl if os name ="nt"sniffer ioctl(socket sio_rcvallsocket rcvall_ontrywhile trueread in packet raw_buffer sniffer recvfrom( )[ create an ip header from the first bytes of the buffer ip_header ip(raw_buffer[ : ]print out the protocol that was detected and the hosts print "protocol% % -% (ip_header protocolip_header src_ addressip_header dst_addresshandle ctrl- except keyboardinterrupt