From: Michael Tremer Date: Fri, 16 Apr 2010 14:58:42 +0000 (+0200) Subject: Speedup the arp packet parsing function. X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=c39c644181083b102f70f397bb6c6df0aa8f9daa;p=oddments%2Fcappie.git Speedup the arp packet parsing function. Finally, do not provide information we do not use later in the dict. --- diff --git a/cappie.py b/cappie.py index 28f9060..036d70c 100644 --- a/cappie.py +++ b/cappie.py @@ -10,6 +10,11 @@ import time from ConfigParser import ConfigParser from threading import Thread +TYPE_ARP = 0 + +OPERATION_REQUEST = 0 +OPERATION_RESPONSE = 1 + def getAllInterfaces(): filters = ("lo", "any") ret = [] @@ -40,34 +45,36 @@ def decode_packet(data): def decode_arp_packet(data): operationmap = { - 1 : "in", - 2 : "out", + 1 : OPERATION_REQUEST, + 2 : OPERATION_RESPONSE, } if not len(data) == 42: raise DecodeError, "Data has wrong length" ret = { - #"hwtype" : data[:2], - "protocol" : val2int(struct.unpack("!2s", data[12:14])[0]), - "hw_addr_size" : val2int(struct.unpack("!1s", data[18:19])[0]), - "hw_prot_size" : val2int(struct.unpack("!1s", data[19:20])[0]), - "operation" : val2int(struct.unpack("!2s", data[20:22])[0]), + "type" : TYPE_ARP, } + #"hwtype" : data[:2], + protocol = val2int(struct.unpack("!2s", data[12:14])[0]) + hw_addr_size = val2int(struct.unpack("!1s", data[18:19])[0]) + hw_prot_size = val2int(struct.unpack("!1s", data[19:20])[0]) + operation = val2int(struct.unpack("!2s", data[20:22])[0]) + # Sanity checks - if not ret["protocol"] == 0x0806: + if not protocol == 0x0806: raise PacketTypeError, "Not an ARP packet" # TODO Must check hwtype here... try: - ret["operation"] = operationmap[ret["operation"]] + ret["operation"] = operationmap[operation] except KeyError: raise DecodeError, "Unknown operation type" - address_length = ret["hw_addr_size"] + ret["hw_prot_size"] - unpack_str = "!%ss%ss" % (ret["hw_addr_size"], ret["hw_prot_size"]) + address_length = hw_addr_size + hw_prot_size + unpack_str = "!%ss%ss" % (hw_addr_size, hw_prot_size) ret["source_address"], ret["source_ip_address"] = \ struct.unpack(unpack_str, data[22:22 + address_length])