当前位置: 首页>>代码示例>>Golang>>正文


Golang PacketConn.ReadFrom方法代码示例

本文整理汇总了Golang中net.PacketConn.ReadFrom方法的典型用法代码示例。如果您正苦于以下问题:Golang PacketConn.ReadFrom方法的具体用法?Golang PacketConn.ReadFrom怎么用?Golang PacketConn.ReadFrom使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net.PacketConn的用法示例。


在下文中一共展示了PacketConn.ReadFrom方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: packetRecv

// receive packets from conn, print them to stdout, and send the address
// of each packet upstream to our master.
// The data packets are assumed to have embedded newlines, which may be
// false.
func packetRecv(conn net.PacketConn, master chan net.Addr) {
	buf := make([]byte, bufsize)
	for {
		var bufStr string

		n, addr, err := conn.ReadFrom(buf[0:])
		if err != nil {
			warnln("error on ReadFrom:", err)
			return
		}

		// TODO: can n ever be 0?
		if dgramhex {
			bufStr = fmt.Sprintf("0x % x\n", buf[:n])
		} else {
			bufStr = fmt.Sprintf("%s", string(buf[:n]))
		}

		if quiet {
			fmt.Printf("%s", bufStr)
		} else {
			fmt.Printf("%s > %s", addr, bufStr)
		}

		// We print packet details before sending the address
		// upstream in case this send blocks.
		master <- addr
	}
}
开发者ID:siebenmann,项目名称:call,代码行数:33,代码来源:call.go

示例2: Serve

func (s *Server) Serve(l net.PacketConn, replyPort int) error {
	var srcAddr *net.UDPAddr
	if s.ServerIP != nil {
		srcAddr = &net.UDPAddr{IP: s.ServerIP}
	}
	buffer := make([]byte, 1500)
	r, err := net.DialUDP("udp", srcAddr, &net.UDPAddr{IP: net.IPv4(255, 255, 255, 255), Port: replyPort})
	if err != nil {
		return err
	}
	defer r.Close()
	for {
		n, _, err := l.ReadFrom(buffer)
		if err != nil {
			return err
		}
		if n < 240 {
			continue
		}
		p := Packet(buffer[:n])
		options := p.ParseOptions()
		msgType := options[OptionDHCPMessageType]
		if len(msgType) != 1 {
			return nil
		}
		// TODO consider more packet validity checks
		if res := s.Handler.ServeDHCP(p, MessageType(msgType[0]), options); res != nil {
			if _, e := r.Write(res); e != nil {
				fmt.Println("Write Error:", e.Error())
			}
		}
	}
	return nil
}
开发者ID:jonsen,项目名称:dhcp4,代码行数:34,代码来源:server.go

示例3: WriteFile

func WriteFile(w io.Writer, conn net.PacketConn, remoteAddress net.Addr, packet []byte, tid uint16) (int, net.Addr, error) {
	// Read data packet
	n, replyAddr, err := conn.ReadFrom(packet)
	if err != nil {
		return n, replyAddr, fmt.Errorf("Error reading packet: %v", err)
	}

	opcode, err := GetOpCode(packet)
	if err != nil {
		return n, replyAddr, fmt.Errorf("Error getting opcode: %v", err)
	}
	if opcode != OpDATA {
		return n, replyAddr, fmt.Errorf("Expected DATA packet, got %v\n", opcode)
	}

	packetTID := binary.BigEndian.Uint16(packet[2:4])
	if packetTID != tid {
		SendError(5, "Unknown transfer id", conn, remoteAddress)
		return n, replyAddr, fmt.Errorf("Expected TID %d, got %d\n", tid, packetTID)
	}

	// Write data to disk
	_, err = w.Write(packet[4:n])
	if err != nil {
		return n, replyAddr, fmt.Errorf("Error writing: %v", err)
	}

	ack := CreateAckPacket(tid)
	_, err = conn.WriteTo(ack, replyAddr)
	if err != nil {
		return n, replyAddr, fmt.Errorf("Error writing ACK packet: %v", err)
	}

	return n, replyAddr, nil
}
开发者ID:ryanslade,项目名称:tftp,代码行数:35,代码来源:common.go

示例4: Serve

// Serve messages received on the given packet listener to the srv.Handler.
func (srv *Server) Serve(l net.PacketConn) error {
	maxMessageBytes := DefaultMaxMessageBytes
	if srv.MaxMessageBytes != 0 {
		maxMessageBytes = srv.MaxMessageBytes
	}
	for {
		buf := make([]byte, maxMessageBytes)
		n, peerAddr, err := l.ReadFrom(buf)
		if err != nil {
			return err
		}
		buf = buf[:n]

		go func(buf []byte, peerAddr net.Addr) {
			// At least one router's UPnP implementation has added a trailing space
			// after "HTTP/1.1" - trim it.
			buf = trailingWhitespaceRx.ReplaceAllLiteral(buf, crlf)

			req, err := http.ReadRequest(bufio.NewReader(bytes.NewBuffer(buf)))
			if err != nil {
				log.Printf("httpu: Failed to parse request: %v", err)
				return
			}
			req.RemoteAddr = peerAddr.String()
			srv.Handler.ServeMessage(req)
			// No need to call req.Body.Close - underlying reader is bytes.Buffer.
		}(buf, peerAddr)
	}
}
开发者ID:CedarLogic,项目名称:go-ethereum,代码行数:30,代码来源:serve.go

示例5: goReceiveDatagrams

func (s *Server) goReceiveDatagrams(packetconn net.PacketConn) {
	s.wait.Add(1)
	go func() {
		defer s.wait.Done()
		for {
			buf := s.datagramPool.Get().([]byte)
			n, addr, err := packetconn.ReadFrom(buf)
			if err == nil {
				// Ignore trailing control characters and NULs
				for ; (n > 0) && (buf[n-1] < 32); n-- {
				}
				if n > 0 {
					var address string
					if addr != nil {
						address = addr.String()
					}
					s.datagramChannel <- DatagramMessage{buf[:n], address}
				}
			} else {
				// there has been an error. Either the server has been killed
				// or may be getting a transitory error due to (e.g.) the
				// interface being shutdown in which case sleep() to avoid busy wait.
				opError, ok := err.(*net.OpError)
				if (ok) && !opError.Temporary() && !opError.Timeout() {
					return
				}
				time.Sleep(10 * time.Millisecond)
			}
		}
	}()
}
开发者ID:cezarsa,项目名称:go-syslog,代码行数:31,代码来源:server.go

示例6: send

// RFC 3489: Clients SHOULD retransmit the request starting with an interval
// of 100ms, doubling every retransmit until the interval reaches 1.6s.
// Retransmissions continue with intervals of 1.6s until a response is
// received, or a total of 9 requests have been sent.
func (v *packet) send(conn net.PacketConn, addr net.Addr) (*packet, error) {
	timeout := 100
	for i := 0; i < 9; i++ {
		length, err := conn.WriteTo(v.bytes(), addr)
		if err != nil {
			return nil, err
		}
		if length != len(v.bytes()) {
			return nil, errors.New("Error in sending data.")
		}
		conn.SetReadDeadline(time.Now().Add(time.Duration(timeout) * time.Millisecond))
		if timeout < 1600 {
			timeout *= 2
		}
		packetBytes := make([]byte, 1024)
		length, _, err = conn.ReadFrom(packetBytes)
		if err == nil {
			return newPacketFromBytes(packetBytes[0:length])
		} else {
			if !err.(net.Error).Timeout() {
				return nil, err
			}
		}
	}
	return nil, nil
}
开发者ID:skycoin,项目名称:skycoin,代码行数:30,代码来源:packet.go

示例7: handleHandshake

func handleHandshake(conn net.PacketConn) error {
	packet := make([]byte, common.MaxPacketSize)

	n, remoteAddr, err := conn.ReadFrom(packet)
	if err != nil {
		return fmt.Errorf("Error reading from connection: %v", err)
	}
	if n == common.MaxPacketSize {
		return fmt.Errorf("Packet too big: %d bytes", n)
	}

	log.Printf("Request from %v", remoteAddr)
	req, err := common.ParseRequestPacket(packet)
	if err != nil {
		return fmt.Errorf("Error parsing request packet: %v", err)
	}

	if !acceptedMode(req.Mode) {
		return fmt.Errorf("Unknown mode: %s", req.Mode)
	}

	handler, ok := handlerMapping[req.OpCode]
	if !ok {
		return fmt.Errorf("No handler for OpCode: %d\n", req.OpCode)
	}
	go handler.serve(remoteAddr, req.Filename)

	return nil
}
开发者ID:ryanslade,项目名称:tftp,代码行数:29,代码来源:server.go

示例8: UDPReader

func UDPReader(conn net.PacketConn) {
	obytes := make([]byte, 64*1024)
	start := time.Now()
	var bcount, count time.Duration

	fmt.Printf("UDP:%s -> REDIS:%[email protected]%s.\n", *listen, key, *redis)

	for {
		bytes := obytes
		n, _, err := conn.ReadFrom(bytes)

		if err != nil {
			fmt.Println(err)
			continue
		}

		count += 1
		bcount += time.Duration(n)

		now := time.Now()
		diff := now.Sub(start)

		if diff > 1e9 {
			fmt.Printf(
				"bps = %s, pps = %d.\n", gutils.FormatBytes(float64(bcount)),
				count,
			)
			start = now
			bcount, count = 0, 0
		}
	}
}
开发者ID:gauravagarwalr,项目名称:gutils,代码行数:32,代码来源:main.go

示例9: getack

func getack(conn net.PacketConn, srcport layers.TCPPort, dstip string) (ack uint32, err error) {
	for {
		b := make([]byte, 4096)
		log.Println("reading from conn")
		var n int
		var addr net.Addr
		n, addr, err = conn.ReadFrom(b)
		if err != nil {
			log.Println("reading..", err)
			return
		} else if addr.String() == dstip {
			// Decode a packet
			packet := gopacket.NewPacket(b[:n], layers.LayerTypeTCP, gopacket.Default)
			// Get the TCP layer from this packet
			if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
				tcp, _ := tcpLayer.(*layers.TCP)
				if tcp.DstPort == srcport {
					if tcp.SYN && tcp.ACK {
						ack = tcp.Seq
					} else {
						err = errors.New("Port is CLOSED")
					}
					return
				}
			}
		} else {
			err = errors.New("Got packet not matching addr")
		}
	}
	return
}
开发者ID:turbobytes,项目名称:initcwndcheck,代码行数:31,代码来源:initcwndcheck.go

示例10: echoServer

func echoServer(Address *string, Message *string) {
	var c net.PacketConn
	var err error

	c, err = net.ListenPacket("sctp", *settings.Address)

	if err != nil {
		log.Printf("Error listening: %v", err)
		os.Exit(-1)
	}
	defer c.Close()

	for {
		msg := make([]byte, 2048)
		log.Printf("Listening on %s", *settings.Address)
		_, addr, err := c.ReadFrom(msg)
		if err != nil {
			log.Printf("Error: %v ", err)
			break
		}
		fmt.Println("Message: " + string(msg))
		c.WriteTo(msg, addr)
	}

}
开发者ID:cyberroadie,项目名称:msc-report-src,代码行数:25,代码来源:EchoSimpleSCTPServer.go

示例11: udpServer

func udpServer(conn net.PacketConn) {
	for {
		bytes := make([]byte, 512)
		n, _, err := conn.ReadFrom(bytes)

		if err != nil {
			fmt.Println(err)
			continue
		}

		bytes = bytes[:n]

		fmt.Println(bytes)

		var job Work
		err = json.Unmarshal(bytes, &job)

		if err != nil {
			fmt.Println(err)
		}

		if job.IP == "" {
			fmt.Println("UDP: got bad json, no IP supplied.", job.String())
			continue
		}

		workers <- job

		fmt.Printf("UDP: %s.\n", job.String())
	}
}
开发者ID:mehulsbhatt,项目名称:pinger-2,代码行数:31,代码来源:udp.go

示例12: receiver

func (s *Server) receiver(c net.PacketConn) {
	//q := (chan<- Message)(s.q)
	buf := make([]byte, 1024)
	for {
		n, _, err := c.ReadFrom(buf)
		if err != nil {
			if !s.shutdown {
				s.l.Fatalln("Read error:", err)
			}
			return
		}
		pkt := buf[:n]

		p := rfc3164.NewParser(pkt)
		if err := p.Parse(); err != nil {
			log.Println(err)
		}
		log := p.Dump()

		m := &Message{
			Time:      time.Now(),
			Priority:  log["priority"].(syslog.Priority),
			Timestamp: log["timestamp"].(time.Time),
			Hostname:  log["hostname"].(string),
			Tag:       log["tag"].(string),
			Content:   log["content"].(string),
		}

		s.passToHandlers(m)
	}
}
开发者ID:inz,项目名称:deis,代码行数:31,代码来源:server.go

示例13: serveTestUdp

func serveTestUdp(in net.PacketConn, pdu_txt string, waiter *sync.WaitGroup) {

	defer func() {
		waiter.Done()
	}()

	var byteArray [10000]byte

	for {
		_, addr, err := in.ReadFrom(byteArray[:])
		if nil != err {
			fmt.Println("[test] read failed", err.Error())
			break
		}

		fmt.Println("[test] recv ok, send at next step")

		bin, err := hex.DecodeString(pdu_txt)
		if nil != err {
			fmt.Println("[test]", err.Error())
		} else {
			if _, err = in.WriteTo(bin, addr); nil != err {
				fmt.Println("[test] write failed", err.Error())
				break
			}
		}
	}
}
开发者ID:runner-mei,项目名称:snmpclient,代码行数:28,代码来源:udp_client_test.go

示例14: ReceivePacket

// ReceivePacket listens for incoming OSC packets and returns the packet and
// client address if one is received.
func (s *Server) ReceivePacket(ctx context.Context, c net.PacketConn) (Packet, net.Addr, error) {
	if deadline, ok := ctx.Deadline(); ok {
		if err := c.SetReadDeadline(deadline); err != nil {
			return nil, nil, err
		}
	}

	go func() {
		select {
		// case <-time.After(200 * time.Millisecond):
		// 	log.Println("Overslept.")
		case <-ctx.Done():
			log.Println(ctx.Err())
		}
	}()

	data := make([]byte, 65535)
	var n, start int
	n, addr, err := c.ReadFrom(data)
	if err != nil {
		return nil, nil, err
	}
	pkt, err := readPacket(bufio.NewReader(bytes.NewBuffer(data)), &start, n)
	return pkt, addr, err
}
开发者ID:kward,项目名称:go-osc,代码行数:27,代码来源:osc.go

示例15: benchmarkReadWriteNetUDP

func benchmarkReadWriteNetUDP(b *testing.B, c net.PacketConn, wb, rb []byte, dst net.Addr) {
	if _, err := c.WriteTo(wb, dst); err != nil {
		b.Fatal(err)
	}
	if _, _, err := c.ReadFrom(rb); err != nil {
		b.Fatal(err)
	}
}
开发者ID:musha68k,项目名称:go-ipfs,代码行数:8,代码来源:readwrite_test.go


注:本文中的net.PacketConn.ReadFrom方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。