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


Golang UDPAddr.String方法代码示例

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


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

示例1: 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
		Debug.Printf("new udp conn %v<-->%v\n", srcaddr, ss.LocalAddr())
		nl.AliveConns += 1
		ok = false
		//full cone
		addr, _ := net.ResolveUDPAddr("udp", ":0")
		conn, err := net.ListenUDP("udp", addr)
		if err != nil {
			return nil, false, err
		}
		c = NewCachedUDPConn(conn)
		nl.Conns[index] = c
		c.SetTimer(index)
		go Pipeloop(ss, srcaddr, c)
	} else {
		//NAT exists
		c, _ = nl.Conns[index]
		c.Refresh()
	}
	err = nil
	return
}
开发者ID:better0332,项目名称:my-shadowsocks-go,代码行数:28,代码来源:conn.go

示例2: Pipeloop

func Pipeloop(ss *UDPConn, srcaddr *net.UDPAddr, remote UDP) {
	buf := pool.Get().([]byte)
	defer pool.Put(buf)
	defer nl.Delete(srcaddr.String())
	for {
		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
		ReqListLock.RLock()
		N, ok := ReqList[raddr.String()]
		ReqListLock.RUnlock()
		if ok {
			ss.WriteToUDP(append(N.Req, buf[:n]...), srcaddr)
		} else {
			header := ParseHeader(raddr)
			ss.WriteToUDP(append(header, buf[:n]...), srcaddr)
		}
		upTraffic(strconv.Itoa(ss.LocalAddr().(*net.UDPAddr).Port), n, srcaddr.IP.String())
	}
}
开发者ID:better0332,项目名称:my-shadowsocks-go,代码行数:31,代码来源:conn.go

示例3: Get

func (nl *NATlist) Get(srcaddr, dstaddr *net.UDPAddr, cn *UDPConn, header []byte) (c *CachedUDPConn, ok bool, err error) {
	nl.Lock()
	defer nl.Unlock()
	index := srcaddr.String() + dstaddr.String()
	_, ok = nl.Conns[index]
	if !ok || nl.Conns[index].Expired {
		//NAT not exists or expired
		delete(nl.Conns, index)
		ok = false
		conn, err := net.DialUDP("udp", nil, dstaddr)
		if err != nil {
			return nil, false, err
		}
		nl.Conns[index] = NewCachedUDPConn(conn)
		c, _ = nl.Conns[index]
		c.SetTimer()
		go Pipeloop(cn, srcaddr, c, header)
	} else {
		//NAT exists
		c, _ = nl.Conns[index]
		c.Refresh()
	}
	err = nil
	return
}
开发者ID:QiussTSE,项目名称:shadowsocks-go-with-traffic-limits,代码行数:25,代码来源:conn.go

示例4: ProcessPacket

// ProcessPacket decodes and processes a received UDP packet, sending responses
// and forwarding the packet on to other clients as appropriate.
func (server *IPXServer) ProcessPacket(packet []byte, addr *net.UDPAddr) {
	var header IPXHeader
	if !header.Decode(packet) {
		return
	}

	if header.IsRegistrationPacket() {
		server.NewClient(&header, addr)
		return
	}

	srcClient, ok := server.clients[addr.String()]
	if !ok {
		return
	}

	// Clients can only send from their own address.
	if header.src.addr != srcClient.ipxAddr {
		return
	}

	srcClient.lastReceiveTime = time.Now()

	if header.IsBroadcast() {
		server.ForwardBroadcastPacket(&header, packet)
	} else {
		server.ForwardPacket(&header, packet)
	}
}
开发者ID:fragglet,项目名称:ipxbox,代码行数:31,代码来源:ipxbox.go

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

示例6: respondWithFallback

func respondWithFallback(raw []uint8, clientMsg *dns.Msg, clientQuestion dns.Question, proxy *net.UDPAddr) {
	LOG.Println("fallback:", clientQuestion, proxy)
	conn, err := net.Dial("udp", proxy.String())
	if err != nil {
		LOG.Fatalln(err)
	}

	conn.Write(raw)

	buffer := make([]byte, 1<<15)
	size, err := conn.Read(buffer)
	if err != nil {
		LOG.Fatalln(err, proxy)
	}

	msg := &dns.Msg{}
	msg.Unpack(buffer[0:size])

	LOG.Println(msg)

	for _, answer := range msg.Answer {
		clientMsg.Answer = append(clientMsg.Answer, answer)
	}

	clientMsg.Rcode = msg.Rcode
	clientMsg.Response = msg.Response
	clientMsg.Authoritative = msg.Authoritative
	clientMsg.Recursion_desired = msg.Recursion_desired
	clientMsg.Recursion_available = msg.Recursion_available
}
开发者ID:manveru,项目名称:godns,代码行数:30,代码来源:godns.go

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

示例8: main

func main() {
	listen := flag.String("addr", ":2055", "Listen address")
	flag.Parse()

	var addr *net.UDPAddr
	var err error
	if addr, err = net.ResolveUDPAddr("udp", *listen); err != nil {
		log.Fatal(err)
	}

	var server *net.UDPConn
	if server, err = net.ListenUDP("udp", addr); err != nil {
		log.Fatal(err)
	}

	decoders := make(map[string]*netflow.Decoder)
	for {
		buf := make([]byte, 8192)
		var remote *net.UDPAddr
		if _, remote, err = server.ReadFromUDP(buf); err != nil {
			log.Printf("error reading from %s: %v\n", remote, err)
			continue
		}

		log.Printf("received %d bytes from %s\n", len(buf), remote)

		d, found := decoders[remote.String()]
		if !found {
			s := session.New()
			d = netflow.NewDecoder(s)
			decoders[remote.String()] = d
		}

		m, err := d.Read(bytes.NewBuffer(buf))
		if err != nil {
			log.Println("decoder error:", err)
			continue
		}

		switch p := m.(type) {
		case *netflow1.Packet:
			netflow1.Dump(p)

		case *netflow5.Packet:
			netflow5.Dump(p)

		case *netflow6.Packet:
			netflow6.Dump(p)

		case *netflow7.Packet:
			netflow7.Dump(p)

		case *netflow9.Packet:
			netflow9.Dump(p)

		case *ipfix.Message:
			ipfix.Dump(p)
		}
	}
}
开发者ID:nyxtom,项目名称:netflow,代码行数:60,代码来源:main.go

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

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

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

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

示例14: NewClient

func (server *Server) NewClient(remoteAddr *net.UDPAddr, nick string, reqId string) (*Client, int) {
	if remoteAddr == nil {
		panic("remoteAddr cannot be nil")
	}
	tmp := server.clients[remoteAddr.String()] // users[clientId]
	if tmp != nil {
		server.sendResponse("LOGIN", remoteAddr, strconv.Itoa(tmp.GetId())+";"+reqId)
		server.sendPastMessages(tmp)
		return nil, tmp.GetId()
	}

	maxId = int(atomic.AddInt32(&server.userId, 1))
	position := firstPosition[maxId%4]
	server.changesServer = true
	server.scoreNewClient(maxId)
	return &Client{
		maxId,
		nick,
		0,
		remoteAddr,
		remoteAddr.String(),
		server,
		float32(position[0]),
		float32(position[1]),
		fullLife,
		false,
		defaultDirection,
		0,
		false,
		false,
		0,
		0,
		0,
	}, 0
}
开发者ID:gophergala2016,项目名称:AngryGophers,代码行数:35,代码来源:client.go

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


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