def usage(): global program_name print("{}, with {!s}".format(program_name, pcap.lib_version().decode("utf-8")), file=sys.stderr) print("Usage: {} [-dO] [ -F file ] [ -m netmask] [ -s snaplen ] dlt " "[ expression ]".format(program_name, "g" if defined("BDEBUG") else ""), file=sys.stderr) print("e.g. ./{} EN10MB host 192.168.1.1".format(program_name), file=sys.stderr) sys.exit(1)
def main(argv=sys.argv): global program_name program_name = os.path.basename(argv[0]) try: opts, args = getopt.getopt(argv[1:], "dF:gm:Os:") except getopt.GetoptError: usage() if is_windows and hasattr(pcap, "wsockinit") and pcap.wsockinit() != 0: return 1 have_fcode = False dflag = 1 if defined("BDEBUG"): gflag = 0 infile = None netmask = pcap.PCAP_NETMASK_UNKNOWN Oflag = 1 snaplen = MAXIMUM_SNAPLEN for opt, optarg in opts: if opt == '-d': dflag += 1 elif opt == 'g': if defined("BDEBUG"): gflag += 1 else: error( "libpcap and filtertest not built with optimizer debugging enabled" ) elif opt == '-F': infile = optarg elif opt == '-O': Oflag = 0 elif opt == '-m': # !!! # try: # addr = socket.inet_pton(socket.AF_INET, optarg) # except socket.error: # if r == 0: # error("invalid netmask {}", optarg) # elif r == -1: # error("invalid netmask {}: {}", optarg, pcap_strerror(errno)) # else: # elif r == 1: # addr = bpf_u_int32(addr) # netmask = addr pass elif opt == '-s': try: long_snaplen = int(optarg) except: error("invalid snaplen {}", optarg) if not (0 <= long_snaplen <= MAXIMUM_SNAPLEN): error("invalid snaplen {}", optarg) elif long_snaplen == 0: # <AK> fix, was: snaplen == 0: snaplen = MAXIMUM_SNAPLEN else: snaplen = long_snaplen else: usage() if not args: usage() dlt_name = args[0] expression = args[1:] dlt = pcap.datalink_name_to_val(dlt_name.encode("utf-8")) if dlt < 0: try: dlt = int(dlt_name) except: error("invalid data link type {!s}", dlt_name) if infile: cmdbuf = read_infile(infile) else: # concatenating arguments with spaces. cmdbuf = " ".join(expression).encode("utf-8") pd = pcap.open_dead(dlt, snaplen) if not pd: error("Can't open fake pcap_t") fcode = pcap.bpf_program() if pcap.compile(pd, ct.byref(fcode), cmdbuf, Oflag, netmask) < 0: error("{!s}", pcap.geterr(pd).decode("utf-8", "ignore")) have_fcode = True if not pcap.bpf_validate(fcode.bf_insns, fcode.bf_len): warning("Filter doesn't pass validation") if defined("BDEBUG"): if cmdbuf: # replace line feed with space mcodes = cmdbuf.decode("utf-8", "ignore") mcodes = mcodes.replace('\r', ' ').replace('\n', ' ') # only show machine code if BDEBUG defined, since dflag > 3 print("machine codes for filter: {}".format(mcodes)) else: print("machine codes for empty filter:") pcap.bpf_dump(ct.byref(fcode), dflag) del cmdbuf if have_fcode: pcap.freecode(ct.byref(fcode)) pcap.close(pd) return 0