From 994814b180895f89bad5f3163010a40d0b5a2fa8 Mon Sep 17 00:00:00 2001 From: Callan Bryant Date: Mon, 2 Mar 2020 21:11:45 +0000 Subject: [PATCH] auto external IP detection --- init.go | 17 +++++++++++++++-- types.go | 2 +- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/init.go b/init.go index 4cf6878..f1edabe 100644 --- a/init.go +++ b/init.go @@ -4,6 +4,7 @@ import ( "fmt" "math/rand" "net" + "strings" "time" ) @@ -14,11 +15,12 @@ func Init() { conf := DsnetConfig{ PrivateKey: privateKey, PresharedKey: presharedKey, - Port: DEFAULT_LISTEN_PORT, + ListenPort: DEFAULT_LISTEN_PORT, Network: getRandomNetwork(), Peers: make([]PeerConfig, 0), Domain: "dsnet", ReportFile: DEFAULT_REPORT_FILE, + ExternalIP: getExternalIP(), } IP := conf.MustAllocateIP() @@ -27,7 +29,7 @@ func Init() { conf.MustSave() - fmt.Printf("Config written to %s. Please edit.", CONFIG_FILE) + fmt.Printf("Config written to %s. Please check/edit.", CONFIG_FILE) } // get a random /22 subnet on 10.0.0.0 (1023 hosts) (or /24?) @@ -43,3 +45,14 @@ func getRandomNetwork() JSONIPNet { }, } } + +func getExternalIP() net.IP { + conn, _ := net.Dial("udp", "8.8.8.8:80") + defer conn.Close() + + localAddr := conn.LocalAddr().String() + IP := net.ParseIP(strings.Split(localAddr, ":")[0]) + + // TODO detect private IP and use icanhazip.com instead + return IP +} diff --git a/types.go b/types.go index 538101d..929483b 100644 --- a/types.go +++ b/types.go @@ -56,7 +56,7 @@ type DsnetConfig struct { // Network is chosen randomly when not specified Network JSONIPNet `validate:"required"` ExternalIP net.IP `validate:"required,cidr"` - ExternalPort int `validate:"gte=1024,lte=65535"` + ListenPort int `validate:"gte=1024,lte=65535"` InternalIP net.IP `validate:"required,cidr"` InternalDNS net.IP `validate:"required,cidr"` // TODO Default subnets to route via VPN