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/ipv6"
17 func TestBPF(t *testing.T) {
18 if runtime.GOOS != "linux" {
19 t.Skipf("not supported on %s", runtime.GOOS)
22 t.Skip("ipv6 is not supported")
25 l, err := net.ListenPacket("udp6", "[::1]:0")
31 p := ipv6.NewPacketConn(l)
33 // This filter accepts UDP packets whose first payload byte is
35 prog, err := bpf.Assemble([]bpf.Instruction{
36 // Load the first byte of the payload (skipping UDP header).
37 bpf.LoadAbsolute{Off: 8, Size: 1},
38 // Select LSB of the byte.
39 bpf.ALUOpConstant{Op: bpf.ALUOpAnd, Val: 1},
41 bpf.JumpIf{Cond: bpf.JumpEqual, Val: 0, SkipFalse: 1},
43 bpf.RetConstant{Val: 4096},
45 bpf.RetConstant{Val: 0},
48 t.Fatalf("compiling BPF: %s", err)
51 if err = p.SetBPF(prog); err != nil {
52 t.Fatalf("attaching filter to Conn: %s", err)
55 s, err := net.Dial("udp6", l.LocalAddr().String())
61 for i := byte(0); i < 10; i++ {
66 l.SetDeadline(time.Now().Add(2 * time.Second))
67 seen := make([]bool, 5)
70 n, _, err := l.ReadFrom(b[:])
72 t.Fatalf("reading from listener: %s", err)
75 t.Fatalf("unexpected packet length, want 1, got %d", n)
78 t.Fatalf("unexpected byte, want 0-9, got %d", b[0])
81 t.Fatalf("got odd byte %d, wanted only even bytes", b[0])
86 for _, v := range seen {