Question about go stun server implement by golang


(才育 郑) #1

hey guys,I recently write some code about p2p comunication,And there is need for NAT recogization ,according to rfc3893,when the first bind request is sent,the server should reply to client with a different local address,it means I should change the local addr of the UDP socket. My question is ,How do I do it?

The following code is I test change local address on server side,But the client could not receieve it.

package main

import (
	"net"
	"qiniupkg.com/x/log.v7"
	"strconv"
	"time"
)

func main(){
	buf := make([]byte,1024)
	laddr ,_ := net.ResolveUDPAddr("udp4","192.168.2.100:4261")
	lis,e := net.ListenUDP("udp4",laddr)
	if nil != e{
		log.Print(e.Error())
	}
	go func() {

		for true{
			lis.SetReadDeadline(time.Now().Add(time.Second*10))
			n, addr,e := lis.ReadFrom(buf)
			if nil != e{
				log.Print(e.Error())
			}
			log.Print("recv " + strconv.Itoa(n) + " from: " + addr.String() )
			laddr ,_ := net.ResolveUDPAddr("udp4","192.168.2.100:122")
			raddr ,_ :=	net.ResolveUDPAddr("udp4",addr.String())
			cnn, e := net.DialUDP("udp4",laddr,raddr)
			if nil !=e {
				log.Print(e.Error())
			}
			cnn.WriteTo([]byte("test"),raddr)
			//raddr ,_ := net.ResolveUDPAddr("udp4","127.0.0.1:134")

		}
	}()

	laddr ,_ = net.ResolveUDPAddr("udp4","192.168.2.100:1122")
	raddr ,_ := net.ResolveUDPAddr("udp4","192.168.2.100:4261")

	cnn, e := net.DialUDP("udp4",laddr,raddr)
	if nil !=e {
		log.Print(e.Error())
	}

	for true{
		buf := make([]byte,1024)
		cnn.Write([]byte{97,98,99})
		time.Sleep(time.Second)
		n,addr,_  := cnn.ReadFrom(buf)
		log.Print(addr)
		log.Print(buf[0:n])
	}
}