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


Golang net.UDPAddr类代码示例

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


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

示例1: startUDP

func startUDP(sink chan Pkt) {
	bind, err := net.ResolveUDPAddr("udp", *bindAddr)
	ready := make(chan struct{})
	if err != nil {
		log.Fatalln("Can not resolve bind address:", err)
	}
	lconn, err := net.ListenUDP("udp", bind)
	if err != nil {
		log.Fatalln("Can not listen on UDP:", err)
	}
	log.Println("Listening on UDP", *bindAddr)
	go func() {
		buf := make([]byte, govpn.MTU)
		var n int
		var raddr *net.UDPAddr
		var err error
		for {
			<-ready
			lconn.SetReadDeadline(time.Now().Add(time.Second))
			n, raddr, err = lconn.ReadFromUDP(buf)
			if err != nil {
				sink <- Pkt{ready: ready}
				continue
			}
			sink <- Pkt{
				raddr.String(),
				UDPSender{lconn, raddr},
				buf[:n],
				ready,
			}
		}
	}()
	ready <- struct{}{}
}
开发者ID:kenjoe41,项目名称:govpn,代码行数:34,代码来源:udp.go

示例2: replyLoop

func (proxy *UDPProxy) replyLoop(proxyConn *net.UDPConn, clientAddr *net.UDPAddr, clientKey *connTrackKey) {
	defer func() {
		proxy.connTrackLock.Lock()
		delete(proxy.connTrackTable, *clientKey)
		proxy.connTrackLock.Unlock()
		utils.Debugf("Done proxying between udp/%v and udp/%v", clientAddr.String(), proxy.backendAddr.String())
		proxyConn.Close()
	}()

	readBuf := make([]byte, UDPBufSize)
	for {
		proxyConn.SetReadDeadline(time.Now().Add(UDPConnTrackTimeout))
	again:
		read, err := proxyConn.Read(readBuf)
		if err != nil {
			if err, ok := err.(*net.OpError); ok && err.Err == syscall.ECONNREFUSED {
				// This will happen if the last write failed
				// (e.g: nothing is actually listening on the
				// proxied port on the container), ignore it
				// and continue until UDPConnTrackTimeout
				// expires:
				goto again
			}
			return
		}
		for i := 0; i != read; {
			written, err := proxy.listener.WriteToUDP(readBuf[i:read], clientAddr)
			if err != nil {
				return
			}
			i += written
			utils.Debugf("Forwarded %v/%v bytes to udp/%v", i, read, clientAddr.String())
		}
	}
}
开发者ID:koheishingai,项目名称:docker,代码行数:35,代码来源:network_proxy.go

示例3: AttemptOne

func AttemptOne(server *net.UDPAddr, ch chan bool) {
	conn, err := net.Dial("udp", server.String())
	res := false
	defer func() {
		ch <- res
	}()
	if err != nil {
		return
	}
	defer conn.Close()
	if err = conn.SetDeadline(time.Now().Add(2 * time.Second)); err != nil {
		return
	}

	request := []byte{
		0, 1, // Binding request
		0, 0, // Message length
		0x21, 0x12, 0xa4, 0x42, // magic
		1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} // TID

	if n, err := conn.Write(request); err != nil || n != len(request) {
		return
	}

	buf := make([]byte, 1024)
	n, err := conn.Read(buf)
	res = (n > 0 && err == nil)
	return
}
开发者ID:danderson,项目名称:damnitisp,代码行数:29,代码来源:main.go

示例4: handlePacket

func (handler *VMessInboundHandler) handlePacket(conn *net.UDPConn, request *protocol.VMessRequest, packet v2net.Packet, clientAddr *net.UDPAddr) {
	ray := handler.vPoint.DispatchToOutbound(packet)
	close(ray.InboundInput())

	responseKey := md5.Sum(request.RequestKey)
	responseIV := md5.Sum(request.RequestIV)

	buffer := alloc.NewBuffer().Clear()
	defer buffer.Release()

	responseWriter, err := v2io.NewAesEncryptWriter(responseKey[:], responseIV[:], buffer)
	if err != nil {
		log.Error("VMessIn: Failed to create encrypt writer: %v", err)
		return
	}
	responseWriter.Write(request.ResponseHeader)

	hasData := false

	if data, ok := <-ray.InboundOutput(); ok {
		hasData = true
		responseWriter.Write(data.Value)
		data.Release()
	}

	if hasData {
		conn.WriteToUDP(buffer.Value, clientAddr)
		log.Info("VMessIn sending %d bytes to %s", buffer.Len(), clientAddr.String())
	}
}
开发者ID:vtroop,项目名称:v2ray-core,代码行数:30,代码来源:vmessin_udp.go

示例5: isValidNonce

func isValidNonce(clientUDPAddr *net.UDPAddr, nonceFromClient int64) bool {
	clientUDPIpPort := clientUDPAddr.String()
	state.nonceMap.RLock()
	isValid := state.nonceMap.Map[clientUDPIpPort] == nonceFromClient
	state.nonceMap.RUnlock()
	return isValid
}
开发者ID:msayson,项目名称:goSamples,代码行数:7,代码来源:fortune-server.go

示例6: Listen_udp

/*
	Starts a UDP listener which will forward received data back to the application using
	the supplied channel.  The listener ID is returned along with a boolean indication
	of success (true) or failure. The uid is the user created session id string that is
	used to send buffers that are not related to a session_data struct.
*/
func (this *Cmgr) Listen_udp(port int, data2usr chan *Sess_data) (uid string, err error) {
	var addr net.UDPAddr

	uid = ""
	addr.IP = net.IPv4(0, 0, 0, 0)
	addr.Port = port
	uconn, err := net.ListenUDP("udp", &addr)
	if err != nil {
		err = fmt.Errorf("unable to create a udp listener on port: %d; %s", port, err)
		return
	}

	uid = fmt.Sprintf("u%d", this.ucount) // successful bind to port
	this.ucount += 1

	cp := new(connection)
	cp.conn = nil
	cp.uconn = uconn
	cp.data2usr = data2usr  // session data written to the channel
	cp.id = uid             // user assigned session id
	this.clist[uid] = cp    // hash for write to session
	go this.conn_reader(cp) // start reader; will discard if data2usr is nil

	this.clist[uid] = cp
	return
}
开发者ID:ScottDaniels,项目名称:gopkgs,代码行数:32,代码来源:connman.go

示例7: newUDPSession

func (listener *Listener) newUDPSession(remote *net.UDPAddr) (*UDPSession, bool) {

	remoteAddrStr := remote.String()
	listener.Lock()
	if sess, ok := listener.remoteAddrs[remoteAddrStr]; ok == true {
		listener.Unlock()
		return sess, true
	}
	listener.Unlock()

	var err error
	var local *net.UDPConn
	if local, err = net.ListenUDP("udp", &net.UDPAddr{}); err != nil {
		//log.Println(err)
		return nil, false
	}
	localAddr := local.LocalAddr().(*net.UDPAddr)

	sess := newUDPSession(listener, remote, local, localAddr)

	listener.Lock()
	listener.remoteAddrs[remoteAddrStr] = sess
	listener.Unlock()

	return sess, false
}
开发者ID:dearplain,项目名称:fast-shadowsocks,代码行数:26,代码来源:skcp.go

示例8: Pipeloop

func Pipeloop(ss *UDPConn, srcaddr *net.UDPAddr, remote UDP) {
	buf := udpBuf.Get()
	defer udpBuf.Put(buf)
	defer nl.Delete(srcaddr.String())
	for {
		remote.SetReadDeadline(time.Now().Add(ss.timeout))
		n, raddr, err := remote.ReadFrom(buf)
		if err != nil {
			if ne, ok := err.(*net.OpError); ok && (ne.Err == syscall.EMFILE || ne.Err == syscall.ENFILE) {
				// log too many open file error
				// EMFILE is process reaches open file limits, ENFILE is system limit
				fmt.Println("[udp]read error:", err)
			} else if ne.Err.Error() == "use of closed network connection" {
				fmt.Println("[udp]Connection Closing:", remote.LocalAddr())
			} else {
				fmt.Println("[udp]error reading from:", remote.LocalAddr(), err)
			}
			return
		}
		// need improvement here
		if N, ok := ReqList[raddr.String()]; ok {
			go ss.WriteToUDP(append(N.Req[:N.ReqLen], buf[:n]...), srcaddr)
		} else {
			header, hlen := ParseHeader(raddr)
			go ss.WriteToUDP(append(header[:hlen], buf[:n]...), srcaddr)
		}
	}
}
开发者ID:orvice,项目名称:shadowsocks-go,代码行数:28,代码来源:udp_conn.go

示例9: Update

// Caller should have lock on UdpSession
func (s *UdpSession) Update(addr *net.UDPAddr) error {
	if s.Addr.String() != addr.String() {
		s.Addr = addr
	}
	s.LastHeartbeat = time.Now()
	return nil
}
开发者ID:ljvblfz,项目名称:slot-golang,代码行数:8,代码来源:udp_session.go

示例10: generateNewNonce

//Generate new nonce for udpAddr and add to nonceMap
func generateNewNonce(udpAddr *net.UDPAddr, nonceMap clientServerUtils.ConcurrentMap) int64 {
	nonce := rand.Int63()
	nonceMap.Lock()
	nonceMap.Map[udpAddr.String()] = nonce
	nonceMap.Unlock()
	return nonce
}
开发者ID:msayson,项目名称:goSamples,代码行数:8,代码来源:auth-server.go

示例11: Get

func (nl *NATlist) Get(srcaddr *net.UDPAddr, ss *UDPConn) (c *CachedUDPConn, ok bool, err error) {
	nl.Lock()
	defer nl.Unlock()
	index := srcaddr.String()
	_, ok = nl.Conns[index]
	if !ok {
		//NAT not exists or expired
		nl.AliveConns += 1
		delete(nl.Conns, index)
		ok = false
		//full cone
		conn, err := net.ListenUDP("udp", &net.UDPAddr{
			IP:   net.IPv6zero,
			Port: 0,
		})
		if err != nil {
			return nil, false, err
		}
		nl.Conns[index] = NewCachedUDPConn(conn)
		c, _ = nl.Conns[index]
		c.SetTimer(index)
		go Pipeloop(ss, srcaddr, c)
	} else {
		//NAT exists
		c, _ = nl.Conns[index]
		c.Refresh()
	}
	err = nil
	return
}
开发者ID:orvice,项目名称:shadowsocks-go,代码行数:30,代码来源:udp_conn.go

示例12: WriteToUDP

func (c *udpConn) WriteToUDP(b []byte, a *net.UDPAddr) (int, error) {
	if atomic.LoadUint32(&c.closed) != 0 {
		return 0, fmt.Errorf("connection is closed")
	}

	c.inet.mutex.Lock()
	defer c.inet.mutex.Unlock()
	dst := c.inet.listeners[a.String()]
	if dst == nil {
		return len(b), nil // drop packet
	}

	b2 := make([]byte, len(b))
	copy(b2, b)

	select {
	case dst.rxChan <- udpPacket{
		Data:        b2,
		Source:      c.addr,
		Destination: *a,
	}:
	default:
		// rx buffer full, drop packet
	}

	return len(b), nil
}
开发者ID:hlandau,项目名称:degoutils,代码行数:27,代码来源:mocknet.go

示例13: HandleClient

// Handle a new client read or write request.
func (s *Server) HandleClient(addr *net.UDPAddr, req pkt.Packet) {
	s.Logger.Debug("Handle Client!")

	reqpkt, ok := req.(*pkt.ReqPacket)
	if !ok {
		s.Logger.Error("Invalid packet type for new connection!")
		return
	}
	// Re-resolve for verification
	clientaddr, err := net.ResolveUDPAddr("udp", addr.String())
	if err != nil {
		s.Logger.Error("Error: %s", err)
		return
	}

	switch reqpkt.GetType() {
	case pkt.RRQ:
		err := s.HandleReadReq(reqpkt, clientaddr)
		if err != nil {
			s.Logger.Error("read request finished, with error:", err)
		}
	case pkt.WRQ:
		err := s.HandleWriteReq(reqpkt, clientaddr)
		if err != nil {
			s.Logger.Error("write request finished, with error:", err)
		}
	default:
		s.Logger.Error("Invalid Packet Type!")
	}
}
开发者ID:brianredbeard,项目名称:astralboot,代码行数:31,代码来源:server.go

示例14: ping

func (d *DHT) ping(queryNode *net.UDPAddr) (nodeId []byte) {

	// Prepare request.
	ch := make(chan interface{})
	reqId := d.getRequestId()
	d.requests[queryNode.String()+string(reqId)] = &Request{ch, time.Now()}

	// Send.
	buf := []byte("d1:ad2:id20:")
	buf = append(buf, d.self.id...)
	buf = append(buf, []byte("e1:q4:ping1:t2:")...)
	buf = append(buf, reqId...)
	buf = append(buf, []byte("1:y1:qe")...)

	d.conn.WriteTo(buf, queryNode)

	// Wait for response.
	res := <-ch

	id, ok := res.(bencode.Dict)["r"].(bencode.Dict)["id"].(string)
	if !ok {
		return nil
	}

	return []byte(id)
}
开发者ID:sheepa,项目名称:videobit,代码行数:26,代码来源:dht.go

示例15: getUserAlias

// It's not found because we are using a different thing
func getUserAlias(who *net.UDPAddr) (string, error) {
	usr, ok := connections[who.String()]
	if !ok {
		return "", errors.New("Your user wasn't found. Please login first")
	}
	return usr.Alias, nil
}
开发者ID:Madrigal,项目名称:GoUDP,代码行数:8,代码来源:GoUDP.go


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