-
Notifications
You must be signed in to change notification settings - Fork 1
/
gochecknat.go
80 lines (65 loc) · 1.54 KB
/
gochecknat.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package gochecknat
import (
"fmt"
"github.com/pion/webrtc/v3"
"sync"
)
type NATInfo struct {
Symmetric bool
IP string
Port uint16
Candidates []webrtc.ICECandidate
}
func GetNATInfo() (info NATInfo, err error) {
// Prepare the configuration
config := webrtc.Configuration{
ICEServers: []webrtc.ICEServer{
{
URLs: []string{"stun:stun1.l.google.com:19302"},
},
},
}
// Create a new RTCPeerConnection
peerConnection, err := webrtc.NewPeerConnection(config)
if err != nil {
panic(err)
}
defer func() {
if cErr := peerConnection.Close(); cErr != nil {
fmt.Printf("cannot close peerConnection: %v\n", cErr)
}
}()
_, err = peerConnection.CreateDataChannel("nat-checker", &webrtc.DataChannelInit{})
if err != nil {
return info, err
}
wg := sync.WaitGroup{}
wg.Add(1)
peerConnection.OnICECandidate(func(candidate *webrtc.ICECandidate) {
if candidate == nil {
wg.Done()
return
}
if candidate.Typ != webrtc.ICECandidateTypeSrflx {
return
}
if candidate.Port != candidate.RelatedPort {
info.Symmetric = true
}
info.IP = candidate.Address
info.Port = candidate.Port
info.Candidates = append(info.Candidates, *candidate)
})
// Create an offer to send to the other process
offer, err := peerConnection.CreateOffer(nil)
if err != nil {
panic(err)
}
// Sets the LocalDescription, and starts our UDP listeners
// Note: this will start the gathering of ICE candidates
if err = peerConnection.SetLocalDescription(offer); err != nil {
panic(err)
}
wg.Wait()
return info, err
}