Ejemplo n.º 1
0
def live_capture(
    device,
    packet_limit=-1,
    snaplen=128,
    drop_to_user=None,
    bpf_expression=None,
):
    global l2_header
    source = ffi.new('const char[]', device)
    errbuf = ffi.new('char[]', libpcap.PCAP_ERRBUF_SIZE)
    handle = libpcap.pcap_create(source, errbuf)
    libpcap.pcap_set_snaplen(handle, snaplen)
    libpcap.pcap_activate(handle)

    pcap_datalink = libpcap.pcap_datalink(handle)
    l2_header = L2_HEADER_STRUCT[pcap_datalink]

    if bpf_expression is not None:
        set_filter(handle, bpf_expression)

    if drop_to_user is not None:
        drop_privileges(drop_to_user)

    try:
        libpcap.pcap_loop(handle, packet_limit, hook, ffi.NULL)
    finally:
        libpcap.pcap_close(handle)
        stop_event.set()
        print('Live capture completed.')
Ejemplo n.º 2
0
def file_capture(file_path, bpf_expression=None):
    global l2_header

    source = ffi.new('const char[]', file_path)
    errbuf = ffi.new('char[]', libpcap.PCAP_ERRBUF_SIZE)
    handle = libpcap.pcap_open_offline(source, errbuf)

    pcap_datalink = libpcap.pcap_datalink(handle)
    l2_header = L2_HEADER_STRUCT[pcap_datalink]

    if bpf_expression is not None:
        set_filter(handle, bpf_expression)

    try:
        libpcap.pcap_loop(handle, -1, hook, ffi.NULL)
    finally:
        libpcap.pcap_close(handle)
        stop_event.set()
        print('File capture completed.')