From 800ebb39be4f07fa7cf112a2915297706b4ee272 Mon Sep 17 00:00:00 2001 From: Alexey Khit Date: Thu, 15 Sep 2022 09:07:53 +0300 Subject: [PATCH] Adds canditates from domain resolver --- cmd/webrtc/candidates.go | 15 +++++---------- pkg/webrtc/helper.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/cmd/webrtc/candidates.go b/cmd/webrtc/candidates.go index e33888b3..c614e4f2 100644 --- a/cmd/webrtc/candidates.go +++ b/cmd/webrtc/candidates.go @@ -5,7 +5,6 @@ import ( "github.com/AlexxIT/go2rtc/pkg/streamer" "github.com/AlexxIT/go2rtc/pkg/webrtc" "github.com/pion/sdp/v3" - "strings" ) var candidates []string @@ -32,15 +31,11 @@ func addCanditates(answer string) (string, error) { } for _, address := range candidates { - if strings.HasPrefix(address, "stun:") { - ip, err := webrtc.GetPublicIP() - if err != nil { - log.Warn().Err(err).Msg("[webrtc] public IP") - continue - } - address = ip.String() + address[4:] - - log.Debug().Str("addr", address).Msg("[webrtc] stun public address") + var err error + address, err = webrtc.LookupIP(address) + if err != nil { + log.Warn().Err(err).Msg("[webrtc] candidate") + continue } cand, err := webrtc.NewCandidate(address) diff --git a/pkg/webrtc/helper.go b/pkg/webrtc/helper.go index 8bab3c74..cd1e9cb8 100644 --- a/pkg/webrtc/helper.go +++ b/pkg/webrtc/helper.go @@ -1,12 +1,14 @@ package webrtc import ( + "fmt" "github.com/AlexxIT/go2rtc/pkg/streamer" "github.com/pion/ice/v2" "github.com/pion/stun" "github.com/pion/webrtc/v3" "net" "strconv" + "strings" ) func NewCandidate(address string) (string, error) { @@ -34,6 +36,31 @@ func NewCandidate(address string) (string, error) { return "candidate:" + cand.Marshal(), nil } +func LookupIP(address string) (string, error) { + if strings.HasPrefix(address, "stun:") { + ip, err := GetPublicIP() + if err != nil { + return "", err + } + return ip.String() + address[4:], nil + } + + if IsIP(address) { + return address, nil + } + + i := strings.IndexByte(address, ':') + ips, err := net.LookupIP(address[:i]) + if err != nil { + return "", err + } + if len(ips) == 0 { + return "", fmt.Errorf("can't resolve: %s", address) + } + + return ips[0].String() + address[i:], nil +} + // GetPublicIP example from https://github.com/pion/stun func GetPublicIP() (net.IP, error) { c, err := stun.Dial("udp", "stun.l.google.com:19302") @@ -63,6 +90,15 @@ func GetPublicIP() (net.IP, error) { return xorAddr.IP, nil } +func IsIP(host string) bool { + for _, i := range host { + if i >= 'A' { + return false + } + } + return true +} + func MimeType(codec *streamer.Codec) string { switch codec.Name { case streamer.CodecH264: