func TestUDPMultiplePacketConnWithMultipleGroupListeners(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } for _, gaddr := range udpMultipleGroupListenerTests { c1, err := net.ListenPacket("udp4", "224.0.0.0:1024") // wildcard address with reusable port if err != nil { t.Fatal(err) } defer c1.Close() c2, err := net.ListenPacket("udp4", "224.0.0.0:1024") // wildcard address with reusable port if err != nil { t.Fatal(err) } defer c2.Close() var ps [2]*ipv4.PacketConn ps[0] = ipv4.NewPacketConn(c1) ps[1] = ipv4.NewPacketConn(c2) var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, ok := nettest.IsMulticastCapable("ip4", &ifi); !ok { continue } for _, p := range ps { if err := p.JoinGroup(&ifi, gaddr); err != nil { t.Fatal(err) } } mift = append(mift, &ift[i]) } for _, ifi := range mift { for _, p := range ps { if err := p.LeaveGroup(ifi, gaddr); err != nil { t.Fatal(err) } } } } }
func TestUDPMultiplePacketConnWithMultipleGroupListeners(t *testing.T) { switch runtime.GOOS { case "dragonfly", "plan9", "solaris", "windows": t.Skipf("not supported on %q", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } for _, gaddr := range udpMultipleGroupListenerTests { c1, err := net.ListenPacket("udp6", "[ff02::]:1024") // wildcard address with reusable port if err != nil { t.Fatalf("net.ListenPacket failed: %v", err) } defer c1.Close() c2, err := net.ListenPacket("udp6", "[ff02::]:1024") // wildcard address with reusable port if err != nil { t.Fatalf("net.ListenPacket failed: %v", err) } defer c2.Close() var ps [2]*ipv6.PacketConn ps[0] = ipv6.NewPacketConn(c1) ps[1] = ipv6.NewPacketConn(c2) var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatalf("net.Interfaces failed: %v", err) } for i, ifi := range ift { if _, ok := isMulticastAvailable(&ifi); !ok { continue } for _, p := range ps { if err := p.JoinGroup(&ifi, gaddr); err != nil { t.Fatalf("ipv6.PacketConn.JoinGroup %v on %v failed: %v", gaddr, ifi, err) } } mift = append(mift, &ift[i]) } for _, ifi := range mift { for _, p := range ps { if err := p.LeaveGroup(ifi, gaddr); err != nil { t.Fatalf("ipv6.PacketConn.LeaveGroup %v on %v failed: %v", gaddr, ifi, err) } } } } }
func TestUDPMultipleConnWithMultipleGroupListeners(t *testing.T) { if testing.Short() || !*testExternal { t.Logf("skipping test to avoid external network") return } for _, tt := range udpMultipleGroupListenerTests { // listen to a group address, actually a wildcard address // with reusable port c1, err := net.ListenPacket("udp4", "224.0.0.0:1024") // see RFC 4727 if err != nil { t.Fatalf("net.ListenPacket failed: %v", err) } defer c1.Close() c2, err := net.ListenPacket("udp4", "224.0.0.0:1024") // see RFC 4727 if err != nil { t.Fatalf("net.ListenPacket failed: %v", err) } defer c2.Close() var ps [2]*ipv4.PacketConn ps[0] = ipv4.NewPacketConn(c1) ps[1] = ipv4.NewPacketConn(c2) var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatalf("net.Interfaces failed: %v", err) } for i, ifi := range ift { if _, ok := isGoodForMulticast(&ifi); !ok { continue } for _, p := range ps { if err := p.JoinGroup(&ifi, tt.gaddr); err != nil { t.Fatalf("ipv4.PacketConn.JoinGroup %v on %v failed: %v", tt.gaddr, ifi, err) } } mift = append(mift, &ift[i]) } for _, ifi := range mift { for _, p := range ps { if err := p.LeaveGroup(ifi, tt.gaddr); err != nil { t.Fatalf("ipv4.PacketConn.LeaveGroup %v on %v failed: %v", tt.gaddr, ifi, err) } } } } }
// addr is used to create a listening UDP conn which becomes the underlying // net.PacketConn for the Socket. func NewSocket(network, addr string) (s *Socket, err error) { pc, err := net.ListenPacket(network, addr) if err != nil { return } return NewSocketFromPacketConn(pc) }
func mustListenPacket(addr string) net.PacketConn { c, err := net.ListenPacket("udp", addr) if err != nil { panic(err) } return c }
func (s *serfDiscovery) Start() error { conn, err := net.ListenPacket("udp4", "0.0.0.0:1024") if err != nil { return err } s.pconn = ipv4.NewPacketConn(conn) if err := s.pconn.JoinGroup(s.iface, &net.UDPAddr{IP: s.group}); err != nil { conn.Close() return err } if err := s.pconn.SetControlMessage(ipv4.FlagDst, true); err != nil { conn.Close() return err } go func() { <-s.stop conn.Close() }() go func() { b := make([]byte, 1500) for { _, cm, src, err := s.pconn.ReadFrom(b) if err != nil { if strings.Contains(err.Error(), "closed network connection") { log.Printf("Closed connection, stopping discovery listener...") return } log.Printf("Failed to read packet: %s", err) continue } if cm.Dst.IsMulticast() { if cm.Dst.Equal(s.group) { sip, _, err := net.SplitHostPort(src.String()) if err != nil { log.Printf("Multicast src '%s' has unexpected format: %s", src, err) } if sip == s.self.String() { continue } err = s.serf.Join(sip) if err != nil { log.Printf("Failed to join serf gossip at '%s': %s ", sip, err) } } else { continue } } } }() return nil }
func TestAnnounceLocalhost(t *testing.T) { t.Parallel() srv := server{ t: map[[20]byte]torrent{ [20]byte{0xa3, 0x56, 0x41, 0x43, 0x74, 0x23, 0xe6, 0x26, 0xd9, 0x38, 0x25, 0x4a, 0x6b, 0x80, 0x49, 0x10, 0xa6, 0x67, 0xa, 0xc1}: { Seeders: 1, Leechers: 2, Peers: []util.CompactPeer{ {[]byte{1, 2, 3, 4}, 5}, {[]byte{6, 7, 8, 9}, 10}, }, }, }, } var err error srv.pc, err = net.ListenPacket("udp", ":0") require.NoError(t, err) defer srv.pc.Close() go func() { require.NoError(t, srv.serveOne()) }() req := AnnounceRequest{ NumWant: -1, Event: Started, } rand.Read(req.PeerId[:]) copy(req.InfoHash[:], []uint8{0xa3, 0x56, 0x41, 0x43, 0x74, 0x23, 0xe6, 0x26, 0xd9, 0x38, 0x25, 0x4a, 0x6b, 0x80, 0x49, 0x10, 0xa6, 0x67, 0xa, 0xc1}) go func() { require.NoError(t, srv.serveOne()) }() ar, err := Announce(fmt.Sprintf("udp://%s/announce", srv.pc.LocalAddr().String()), &req) require.NoError(t, err) assert.EqualValues(t, 1, ar.Seeders) assert.EqualValues(t, 2, len(ar.Peers)) }
// NewUDPHook returns logrus-compatible hook that sends data to UDP socket func NewUDPHook(opts ...UDPOptionSetter) (*UDPHook, error) { f := &UDPHook{} for _, o := range opts { o(f) } if f.Clock == nil { f.Clock = clockwork.NewRealClock() } if f.clientNet == "" { f.clientNet = UDPDefaultNet } if f.clientAddr == "" { f.clientAddr = UDPDefaultAddr } addr, err := net.ResolveUDPAddr(f.clientNet, f.clientAddr) if err != nil { return nil, Wrap(err) } conn, err := net.ListenPacket("udp", ":0") if err != nil { return nil, Wrap(err) } f.addr = addr f.conn = conn.(*net.UDPConn) return f, nil }
func (nr *NetworkReader) Start() { connection, err := net.ListenPacket("udp4", nr.host) if err != nil { nr.logger.Fatalf("Failed to listen on port. %s", err) } nr.logger.Infof("Listening on port %s", nr.host) nr.lock.Lock() nr.connection = connection nr.lock.Unlock() readBuffer := make([]byte, 65535) //buffer with size = max theoretical UDP size for { readCount, senderAddr, err := connection.ReadFrom(readBuffer) if err != nil { nr.logger.Debugf("Error while reading. %s", err) return } nr.logger.Debugf("NetworkReader: Read %d bytes from address %s", readCount, senderAddr) readData := make([]byte, readCount) //pass on buffer in size only of read data copy(readData, readBuffer[:readCount]) atomic.AddUint64(&nr.receivedMessageCount, 1) atomic.AddUint64(&nr.receivedByteCount, uint64(readCount)) metrics.BatchIncrementCounter(nr.contextName + ".receivedMessageCount") metrics.BatchAddCounter(nr.contextName+".receivedByteCount", uint64(readCount)) nr.writer.Write(readData) } }
func TestPacketConnMulticastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } m, ok := nettest.SupportsRawIPSocket() for _, tt := range packetConnMulticastSocketOptionTests { if tt.net == "ip6" && !ok { t.Log(m) continue } c, err := net.ListenPacket(tt.net+tt.proto, tt.addr) if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) defer p.Close() if tt.src == nil { testMulticastSocketOptions(t, p, ifi, tt.grp) } else { testSourceSpecificMulticastSocketOptions(t, p, ifi, tt.grp, tt.src) } } }
func icmpListen(v6 bool, ch chan ICMPMessage) { afnet := "ip4:icmp" if v6 { afnet = "ip6:ipv6-icmp" } c, err := net.ListenPacket(afnet, "") if err != nil { debug.Printf("ListenPacket failed: %v", err) return } defer c.Close() rawICMP := make([]byte, 256) for { _, fromAddr, err := c.ReadFrom(rawICMP) if err != nil { debug.Printf("ReadFrom failed: %v", err) return } msg, err := parseICMP(v6, fromAddr, rawICMP) if err != nil { debug.Printf("parseICMP failed: %v", err) continue } ch <- msg } }
func newLocalPacketListener(network string) (net.PacketConn, error) { switch network { case "udp": if c, err := net.ListenPacket("udp4", "127.0.0.1:0"); err == nil { return c, nil } return net.ListenPacket("udp6", "[::1]:0") case "udp4": return net.ListenPacket("udp4", "127.0.0.1:0") case "udp6": return net.ListenPacket("udp6", "[::1]:0") case "unixgram": return net.ListenPacket(network, localPath()) } return nil, fmt.Errorf("%s is not supported", network) }
func main() { flag.Parse() ip, n, err := net.ParseCIDR(*src) if err != nil { log.Fatal(err) } c, err := net.ListenPacket("udp", net.JoinHostPort("0.0.0.0", fmt.Sprintf("%d", *port))) if err != nil { log.Fatal(err) } defer c.Close() go func() { dst := broadcast(n) for { if err := advert(c, ip, dst, n); err != nil { log.Println(err) } time.Sleep(5 * time.Second) } }() b := make([]byte, 8192) for { n, peer, err := c.ReadFrom(b) if err != nil { log.Println(err) continue } log.Printf("%d bytes rcvd from %v, %q\n", n, peer, string(b[:n])) } }
func newUDPEchoServer() (*udpEchoServer, error) { packetconn, err := net.ListenPacket("udp", ":0") if err != nil { return nil, err } return &udpEchoServer{packetconn}, nil }
func main() { listen = flag.String("listen", "127.0.0.1:4443", "Listen on this address.") quite = flag.Bool("quite", false, "Quite mode.") statsonly = flag.Bool( "statsonly", false, "Only prints stats on stdout and discard data.", ) flag.Parse() conn, err := net.ListenPacket("udp4", *listen) if err != nil { fmt.Println(err) return } if !*quite { if *statsonly { fmt.Printf( "UDP: Server started on %s in statsonly mode.\n", *listen, ) } else { fmt.Printf("UDP: Server started on %s.\n", *listen) } } obytes := make([]byte, 64*1024) start := time.Now() var bcount, count time.Duration for { bytes := obytes n, _, err := conn.ReadFrom(bytes) if err != nil { fmt.Println(err) continue } if *statsonly { count += 1 bcount += time.Duration(n) now := time.Now() diff := now.Sub(start) if diff > 1e9 { fmt.Printf( "bps = %sps, pps = %d.\n", gutils.FormatBytes(float64(bcount)), count, ) start = now bcount, count = 0, 0 } } else { bytes = bytes[:n] fmt.Printf(string(bytes)) } } }
// Fire fires the event to the ELK beat func (elk *UDPHook) Fire(e *log.Entry) error { // Make a copy to safely modify entry := e.WithFields(nil) if frameNo := findFrame(); frameNo != -1 { t := newTrace(frameNo-1, nil) entry.Data[FileField] = t.String() entry.Data[FunctionField] = t.Func() } data, err := json.Marshal(Frame{ Time: elk.Clock.Now().UTC(), Type: "trace", Entry: entry.Data, Message: entry.Message, Level: entry.Level.String(), }) if err != nil { return Wrap(err) } c, err := net.ListenPacket("udp", ":0") if err != nil { return Wrap(err) } ra, err := net.ResolveUDPAddr("udp", "127.0.0.1:5000") if err != nil { return Wrap(err) } _, err = (c.(*net.UDPConn)).WriteToUDP(data, ra) return Wrap(err) }
func TestRawConnUnicastSocketOptions(t *testing.T) { switch runtime.GOOS { case "plan9": t.Skipf("not supported on %q", runtime.GOOS) } if os.Getuid() != 0 { t.Skip("must be root") } ifi := loopbackInterface() if ifi == nil { t.Skipf("not available on %q", runtime.GOOS) } c, err := net.ListenPacket("ip4:icmp", "127.0.0.1") if err != nil { t.Fatalf("net.ListenPacket failed: %v", err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatalf("ipv4.NewRawConn failed: %v", err) } testUnicastSocketOptions(t, r) }
func main() { flag.Parse() c, err := net.ListenPacket("udp", net.JoinHostPort(*group, "0")) if err != nil { log.Fatal(err) } p := ipv4.NewPacketConn(c) defer p.Close() dst, err := net.ResolveUDPAddr("udp", net.JoinHostPort(*group, *port)) if err != nil { log.Fatal(err) } log.Println(c.LocalAddr()) go sender(p, dst) sig := make(chan os.Signal) signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) for { select { case <-sig: os.Exit(0) } } }
func TestSetICMPFilter(t *testing.T) { switch runtime.GOOS { case "linux": default: t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket("ip4:icmp", "127.0.0.1") if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) var f ipv4.ICMPFilter f.SetAll(true) f.Accept(ipv4.ICMPTypeEcho) f.Accept(ipv4.ICMPTypeEchoReply) if err := p.SetICMPFilter(&f); err != nil { t.Fatal(err) } kf, err := p.ICMPFilter() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(kf, &f) { t.Fatalf("got %#v; want %#v", kf, f) } }
func TestPacketConnUnicastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9": t.Skipf("not supported on %s", runtime.GOOS) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } m, ok := nettest.SupportsRawIPSocket() for _, tt := range packetConnUnicastSocketOptionTests { if tt.net == "ip4" && !ok { t.Log(m) continue } c, err := net.ListenPacket(tt.net+tt.proto, tt.addr) if err != nil { t.Fatal(err) } defer c.Close() testUnicastSocketOptions(t, ipv4.NewPacketConn(c)) } }
func startFakeMetron() (metronReceivedBufferPtr *[]byte, port string) { connection, err := net.ListenPacket("udp", "") if err != nil { Fail("Error starting the integration test: Could not listen for udp packets on os-assigned port: " + err.Error()) } metronReceivedBuffer := make([]byte, maxUpdDatagramSize) go func() { defer connection.Close() for { _, _, err = connection.ReadFrom(metronReceivedBuffer) if err != nil { panic(err) } if string(metronReceivedBuffer) != string(make([]byte, maxUpdDatagramSize)) { fmt.Fprintf(GinkgoWriter, "\nRead UDP Packet: %s\n", metronReceivedBuffer) } } }() _, listenPort, err := net.SplitHostPort(connection.LocalAddr().String()) Expect(err).NotTo(HaveOccurred()) return &metronReceivedBuffer, listenPort }
func newBaseConn(n string, addr *Addr) (*baseConn, error) { udpnet, err := utp2udp(n) if err != nil { return nil, err } var s string if addr != nil { s = addr.String() } else { s = ":0" } conn, err := net.ListenPacket(udpnet, s) if err != nil { return nil, err } c := &baseConn{ conn: conn, synPackets: newPacketRingBuffer(packetBufferSize), outOfBandPackets: newPacketRingBuffer(packetBufferSize), handlers: make(map[uint16]packetHandler), } c.Register(-1, nil) go c.recvLoop() return c, nil }
func NewNetAcuity(addrStr string) (NetAcuity, error) { // NetAcuity server address addr, err := net.ResolveUDPAddr("udp", addrStr) if err != nil { return nil, err } // Local UDP address to receive packets back from NetAcuity server pc, err := net.ListenPacket("udp", "0.0.0.0:0") if err != nil { return nil, err } na := &netAcuity{ addr: addr, conn: pc.(*net.UDPConn), timeout: DefaultTimeout, maxAttempts: defaultMaxAttempts, shutdownCh: make(chan struct{}), requestsLock: sync.Mutex{}, requests: make(map[string]chan *netAcuityResponse), apiId: rand.Int(), } go na.receive() return na, nil }
func TestPacketConnReadWriteUnicastUDP(t *testing.T) { switch runtime.GOOS { case "dragonfly", "plan9", "solaris", "windows": t.Skipf("not supported on %q", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } c, err := net.ListenPacket("udp6", "[::1]:0") if err != nil { t.Fatalf("net.ListenPacket failed: %v", err) } defer c.Close() p := ipv6.NewPacketConn(c) defer p.Close() dst, err := net.ResolveUDPAddr("udp6", c.LocalAddr().String()) if err != nil { t.Fatalf("net.ResolveUDPAddr failed: %v", err) } cm := ipv6.ControlMessage{ TrafficClass: DiffServAF11 | CongestionExperienced, Src: net.IPv6loopback, Dst: net.IPv6loopback, } cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU ifi := loopbackInterface() if ifi != nil { cm.IfIndex = ifi.Index } wb := []byte("HELLO-R-U-THERE") for i, toggle := range []bool{true, false, true} { if err := p.SetControlMessage(cf, toggle); err != nil { t.Fatalf("ipv6.PacketConn.SetControlMessage failed: %v", err) } cm.HopLimit = i + 1 if err := p.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatalf("ipv6.PacketConn.SetWriteDeadline failed: %v", err) } if n, err := p.WriteTo(wb, &cm, dst); err != nil { t.Fatalf("ipv6.PacketConn.WriteTo failed: %v", err) } else if n != len(wb) { t.Fatalf("ipv6.PacketConn.WriteTo failed: short write: %v", n) } rb := make([]byte, 128) if err := p.SetReadDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatalf("ipv6.PacketConn.SetReadDeadline failed: %v", err) } if n, cm, _, err := p.ReadFrom(rb); err != nil { t.Fatalf("ipv6.PacketConn.ReadFrom failed: %v", err) } else if !bytes.Equal(rb[:n], wb) { t.Fatalf("got %v; expected %v", rb[:n], wb) } else { t.Logf("rcvd cmsg: %v", cm) } } }
func TestRawConnUnicastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9": t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } c, err := net.ListenPacket("ip4:icmp", "127.0.0.1") if err != nil { t.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } testUnicastSocketOptions(t, r) }
func startFakeMetron() (metronReceivedBufferPtr *[]byte, port string) { connection, err := net.ListenPacket("udp", "") //listen on some free port if err != nil { Fail("Error starting the integration test: Could not listen for udp packets on os-assigned port: " + err.Error()) } metronReceivedBuffer := make([]byte, maxUpdDatagramSize) go func() { defer connection.Close() for { _, _, err = connection.ReadFrom(metronReceivedBuffer) if err != nil { panic(err) } if string(metronReceivedBuffer) != string(make([]byte, maxUpdDatagramSize)) { //output if not empty fmt.Fprint(GinkgoWriter, "\nRead UDP Packet: ", string(metronReceivedBuffer), "\n") } } }() portMatch := regexp.MustCompile(`\[::\]:(\d+)`) port = portMatch.FindStringSubmatch(connection.LocalAddr().String())[1] return &metronReceivedBuffer, port }
func TestSetICMPFilter(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket("ip6:ipv6-icmp", "::1") if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) var f ipv6.ICMPFilter f.SetAll(true) f.Accept(ipv6.ICMPTypeEchoRequest) f.Accept(ipv6.ICMPTypeEchoReply) if err := p.SetICMPFilter(&f); err != nil { t.Fatal(err) } kf, err := p.ICMPFilter() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(kf, &f) { t.Fatalf("got %#v; want %#v", kf, f) } }
func listener(prot string, url string, finish <-chan bool, lines chan<- string) { listener, err := net.ListenPacket(prot, url) if err != nil { log.Print("ListenPacket Failure: ", err, " not listening") return } go func() { for { buffer := make([]byte, 1024) bytesRead, _, err := listener.ReadFrom(buffer[0:]) if err != nil { log.Print("Listener: Unable to Read Packet!") } else { lines <- string(buffer[0:bytesRead]) } } }() for { select { case <-finish: log.Print("listener: signalled to end, closing") return } } }
func (agentListener *agentListener) Start() chan []byte { dataChannel := make(chan []byte) connection, err := net.ListenPacket("udp", agentListener.host) logger.Infof("Listening on port %s", agentListener.host) if err != nil { logger.Fatalf("Failed to listen on port. %s", err) panic(err) } go func() { readBuffer := make([]byte, 65535) //buffer with size = max theoretical UDP size for { readCount, senderAddr, err := connection.ReadFrom(readBuffer) if err != nil { logger.Debugf("Error while reading. %s", err) } logger.Debugf("Read %d bytes from address %s", readCount, senderAddr) readData := make([]byte, readCount) //pass on buffer in size only of read data copy(readData, readBuffer[:readCount]) dataChannel <- readData } }() return dataChannel }
func TestSetICMPFilter(t *testing.T) { switch runtime.GOOS { case "plan9", "windows": t.Skipf("not supported on %q", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if os.Getuid() != 0 { t.Skip("must be root") } c, err := net.ListenPacket("ip6:ipv6-icmp", "::1") if err != nil { t.Fatalf("net.ListenPacket failed: %v", err) } defer c.Close() p := ipv6.NewPacketConn(c) var f ipv6.ICMPFilter f.SetAll(true) f.Set(ipv6.ICMPTypeEchoRequest, false) f.Set(ipv6.ICMPTypeEchoReply, false) if err := p.SetICMPFilter(&f); err != nil { t.Fatalf("ipv6.PacketConn.SetICMPFilter failed: %v", err) } kf, err := p.ICMPFilter() if err != nil { t.Fatalf("ipv6.PacketConn.ICMPFilter failed: %v", err) } if !reflect.DeepEqual(kf, &f) { t.Fatalf("got unexpected filter %#v; expected %#v", kf, f) } }