/
net_functions.go
71 lines (59 loc) · 1.34 KB
/
net_functions.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
package lib
// Ask the kernel for a free open port that is ready to use
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
log "github.com/Sirupsen/logrus"
"github.com/prestonTao/upnp"
)
func RandomFreePort() int {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
panic(err)
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
panic(err)
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port
}
func OpenUpnpPort(port int) bool {
mapping := new(upnp.Upnp)
if err := mapping.AddPortMapping(port, port, "TCP"); err == nil {
log.Debug("success !")
return true
// remove port mapping in gatway
// mapping.Reclaim()
}
log.Debug("fail !")
return false
}
func GetLocalIps(port int) []string {
listIps := []string{}
host, _ := os.Hostname()
addrs, _ := net.LookupIP(host)
for _, addr := range addrs {
if ipv4 := addr.To4(); ipv4 != nil {
listIps = append(listIps, fmt.Sprintf("http://%s:%v", ipv4, port))
}
}
return listIps
}
func GetPublicIps(port int) []string {
listIps := []string{}
resp, err := http.Get("http://myexternalip.com/raw")
if err == nil {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err == nil {
lines := strings.Split(string(body), "\n")
listIps = append(listIps, fmt.Sprintf("http://%s:%v", lines[0], port))
}
}
return listIps
}