-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathutils.go
86 lines (73 loc) · 1.75 KB
/
utils.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
81
82
83
84
85
86
package sipgox
import (
"fmt"
"math/rand"
"net"
"strings"
"github.com/emiago/sipgo/sip"
)
// We are lazy to write full sip uris
func CheckLazySipUri(target string, destOverwrite string) string {
if !strings.Contains(target, "@") {
target = target + "@" + destOverwrite
}
if !strings.HasPrefix(target, "sip") {
target = "sip:" + target
}
return target
}
func resolveHostIPWithTarget(network string, targetAddr string) (net.IP, error) {
tip, _, _ := sip.ParseAddr(targetAddr)
ip := net.ParseIP(tip)
if network == "udp" {
if ip != nil {
if ip.IsLoopback() {
// TO avoid UDP COnnected connection problem hitting different subnet
return net.ParseIP("127.0.0.99"), nil
}
}
}
rip, _, err := sip.ResolveInterfacesIP("ip4", nil)
return rip, err
}
func FindFreeInterfaceHostPort(network string, targetAddr string) (ip net.IP, port int, err error) {
// Go with random
// use empheral instead of this
ip, err = resolveHostIPWithTarget(network, targetAddr)
if err != nil {
return ip, port, err
}
port, err = findFreePort(network, ip)
if err != nil {
return
}
if port == 0 {
return ip, port, fmt.Errorf("failed to find free port")
}
return ip, port, err
}
func findFreePort(network string, ip net.IP) (int, error) {
switch network {
case "udp":
var l *net.UDPConn
l, err := net.ListenUDP("udp", &net.UDPAddr{IP: ip})
if err != nil {
return 0, err
}
l.Close()
// defer l.Close()
port := l.LocalAddr().(*net.UDPAddr).Port
return port, nil
case "tcp", "ws", "tls", "wss":
var l *net.TCPListener
l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: ip})
if err != nil {
return 0, err
}
defer l.Close()
port := l.Addr().(*net.TCPAddr).Port
return port, nil
default:
return rand.Intn(9999) + 6000, nil
}
}