以下の記事を参考に Go の実装に置き換えてみた。
以下のパッケージ使って同等のことが割と簡単に実装できた。
Go言語楽しい。
実行結果
# go run webrtc/main.go
2020/01/06 23:31:08 Local IP Address: 192.168.xxx.xxx
2020/01/06 23:31:08 Public IP Address: 113.xxx.xxx.xxx
実装
main.go
package main
import (
"log"
"os"
"github.com/pion/webrtc/v2"
)
func main() {
config := webrtc.Configuration{
ICEServers: []webrtc.ICEServer{
{
URLs: []string{"stun:stun.l.google.com:19302"},
},
},
}
// generate a new connection
peerConnection, err := webrtc.NewPeerConnection(config)
if err != nil {
log.Fatal(err)
}
peerConnection.OnICECandidate(func(c *webrtc.ICECandidate) {
if c == nil {
os.Exit(0)
}
switch c.Typ {
case webrtc.ICECandidateTypeHost:
log.Println("Local IP Address:", c.Address)
case webrtc.ICECandidateTypeSrflx:
log.Println("Public IP Address:", c.Address)
}
})
if _, err := peerConnection.CreateDataChannel("", nil); err != nil {
log.Fatal(err)
}
offer, err := peerConnection.CreateOffer(nil)
if err != nil {
log.Fatal(err)
}
if err = peerConnection.SetLocalDescription(offer); err != nil {
log.Fatal(err)
}
// block forever
select {}
}