本文整理汇总了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
}
示例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())
}
}
示例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
}
示例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)
}
}
示例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
}
示例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
}
示例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
}
示例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)
}
}
}
示例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
}
示例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
}
示例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!")
}
}
示例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)
}
示例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{}{}
}
示例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
}
示例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)
}
}
}