google / gopacket

Provides packet processing capabilities for Go
BSD 3-Clause "New" or "Revised" License
6.32k stars 1.13k forks source link

afpacket example with filter #503

Closed gmonk closed 5 years ago

gmonk commented 6 years ago

Is it possible to assign bpf while using afpacket similar to pcap ? and if so could you provide an example

Thanks

negbie commented 6 years ago
type afpacketHandle struct {
    TPacket *afpacket.TPacket
}

func (h *afpacketHandle) ReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error) {
    return h.TPacket.ReadPacketData()
}

func (h *afpacketHandle) ZeroCopyReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error) {
    return h.TPacket.ZeroCopyReadPacketData()
}

func (h *afpacketHandle) SetBPFFilter(filter string, snaplen int) (err error) {
    pcapBPF, err := pcap.CompileBPFFilter(layers.LinkTypeEthernet, snaplen, filter)
    if err != nil {
        return err
    }
    bpfIns := []bpf.RawInstruction{}
    for _, ins := range pcapBPF {
        bpfIns2 := bpf.RawInstruction{
            Op: ins.Code,
            Jt: ins.Jt,
            Jf: ins.Jf,
            K:  ins.K,
        }
        bpfIns = append(bpfIns, bpfIns2)
    }
    if h.TPacket.SetBPF(bpfIns); err != nil {
        return err
    }
    return h.TPacket.SetBPF(bpfIns)
}
gmonk commented 6 years ago

Awsome.. Thank you for this

gconnell commented 6 years ago

Thanks, negbie! Would either you or gmonk like to add a quick code sample to the examples/ directory?

negbie commented 6 years ago

Sure, I will do it in the following days.

negbie commented 6 years ago

If this https://github.com/google/gopacket/pull/460/commits/511567d6ae8083f45de05b8c00a4a300b51efa3b is too much and you only want a additional function which takes a BPF filter string and returns []bpf.RawInstruction{} so it could be used with TPacket.SetBPF(), tell me.

notti commented 5 years ago

Example code in #460 was merged, so closing this