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


Golang net.PacketConn类代码示例

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


在下文中一共展示了PacketConn类的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: 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

示例4: 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

示例5: 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

示例6: sendAbort

// sends an ABORT packet to the specified peer
func sendAbort(c net.PacketConn, addr net.Addr, tag []byte) {
	p := NewPacket(4)
	p.D[0] = byte(PacketAbort)
	copy(p.D[1:4], tag)
	c.WriteTo(p.D, addr)
	p.Free()
}
开发者ID:sunnyboy00,项目名称:gomnet,代码行数:8,代码来源:listener.go

示例7: 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

示例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: test1

func test1(conn net.PacketConn, addr net.Addr, softwareName string) (*packet, net.Addr, bool, *Host, error) {
	packet, err := sendBindingReq(conn, addr, softwareName)
	if err != nil {
		return nil, nil, false, nil, err
	}
	if packet == nil {
		return nil, nil, false, nil, nil
	}

	// RFC 3489 doesn't require the server return XOR mapped address.
	hostMappedAddr := packet.xorMappedAddr()
	if hostMappedAddr == nil {
		hostMappedAddr = packet.mappedAddr()
		if hostMappedAddr == nil {
			return nil, nil, false, nil, errors.New("No mapped address.")
		}
	}

	identical := isLocalAddress(conn.LocalAddr().String(), hostMappedAddr.TransportAddr())

	hostChangedAddr := packet.changedAddr()
	if hostChangedAddr == nil {
		return packet, nil, identical, hostMappedAddr, nil
	}
	changedAddrStr := hostChangedAddr.TransportAddr()
	changedAddr, err := net.ResolveUDPAddr("udp", changedAddrStr)
	if err != nil {
		return nil, nil, false, nil, errors.New("Failed to resolve changed address.")
	}
	return packet, changedAddr, identical, hostMappedAddr, nil
}
开发者ID:skycoin,项目名称:skycoin,代码行数:31,代码来源:discover.go

示例10: 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

示例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: 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

示例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: sendPacket

func sendPacket(conn net.PacketConn, destination *net.IPAddr, payload []byte, seq int) {
	packet := make([]byte, len(payload)+8)
	packet[0] = 8
	packet[1] = 0
	packet[4] = uint8(os.Getpid() >> 8)
	packet[5] = uint8(os.Getpid() & 0xff)
	packet[6] = uint8(seq >> 8)
	packet[7] = uint8(seq & 0xff)
	copy(packet[8:], payload)

	cklen := len(packet)
	cksum := uint32(0)
	for i := 0; i < cklen-1; i += 2 {
		cksum += uint32(packet[i+1])<<8 | uint32(packet[i])
	}
	if cklen&1 == 1 {
		cksum += uint32(packet[cklen-1])
	}
	cksum = (cksum >> 16) + (cksum & 0xffff)
	cksum = cksum + (cksum >> 16)

	packet[2] ^= uint8(^cksum & 0xff)
	packet[3] ^= uint8(^cksum >> 8)

	_, err := conn.WriteTo(packet, destination)
	if err != nil {
		panic(err)
	}
}
开发者ID:ragnar-johannsson,项目名称:icmp-echo-file,代码行数:29,代码来源:icmp-echo-file.go

示例15: 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


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