1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
13 "golang.org/x/net/bpf"
14 "golang.org/x/net/ipv4"
17 func TestBPF(t *testing.T) {
18 if runtime.GOOS != "linux" {
19 t.Skipf("not supported on %s", runtime.GOOS)
22 l, err := net.ListenPacket("udp4", "127.0.0.1:0")
28 p := ipv4.NewPacketConn(l)
30 // This filter accepts UDP packets whose first payload byte is
32 prog, err := bpf.Assemble([]bpf.Instruction{
33 // Load the first byte of the payload (skipping UDP header).
34 bpf.LoadAbsolute{Off: 8, Size: 1},
35 // Select LSB of the byte.
36 bpf.ALUOpConstant{Op: bpf.ALUOpAnd, Val: 1},
38 bpf.JumpIf{Cond: bpf.JumpEqual, Val: 0, SkipFalse: 1},
40 bpf.RetConstant{Val: 4096},
42 bpf.RetConstant{Val: 0},
45 t.Fatalf("compiling BPF: %s", err)
48 if err = p.SetBPF(prog); err != nil {
49 t.Fatalf("attaching filter to Conn: %s", err)
52 s, err := net.Dial("udp4", l.LocalAddr().String())
58 for i := byte(0); i < 10; i++ {
63 l.SetDeadline(time.Now().Add(2 * time.Second))
64 seen := make([]bool, 5)
67 n, _, err := l.ReadFrom(b[:])
69 t.Fatalf("reading from listener: %s", err)
72 t.Fatalf("unexpected packet length, want 1, got %d", n)
75 t.Fatalf("unexpected byte, want 0-9, got %d", b[0])
78 t.Fatalf("got odd byte %d, wanted only even bytes", b[0])
83 for _, v := range seen {