Created
June 23, 2020 16:03
-
-
Save bamchoh/6c3464b4d99b21e3334cd65525e33dfe to your computer and use it in GitHub Desktop.
STUN server over UDP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"net" | |
"os" | |
"time" | |
) | |
var port = flag.Int("port", 0, "") | |
func main() { | |
flag.Parse() | |
uaddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf(":%d", *port)) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("stun server started") | |
conn, err := net.ListenUDP("udp4", uaddr) | |
if err != nil { | |
panic(err) | |
} | |
buf := make([]byte, 1024) | |
addrs := make([]net.Addr, 0) | |
for { | |
n, addr, err := conn.ReadFromUDP(buf) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
go func() { | |
fmt.Println(addr.String(), string(buf[:n])) | |
if len(addrs) == 0 { | |
addrs = append(addrs, addr) | |
} else { | |
conn.WriteTo([]byte("addr:"+addr.String()), addrs[0]) | |
time.Sleep(1 * time.Second) | |
conn.WriteTo([]byte("addr:"+addrs[0].String()), addr) | |
addrs = make([]net.Addr, 0) | |
} | |
}() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment