functions to get local/public IP

This commit is contained in:
Zack Scholl 2018-09-23 05:27:32 -07:00
parent 7799d2fb58
commit f3df177ba2
2 changed files with 50 additions and 0 deletions

39
src/utils/ip.go Normal file
View File

@ -0,0 +1,39 @@
package utils
import (
"io/ioutil"
"log"
"net"
"net/http"
"strings"
)
func PublicIP() (ip string, err error) {
resp, err := http.Get("https://canhazip.com")
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
ip = strings.TrimSpace(string(bodyBytes))
}
return
}
// Get preferred outbound ip of this machine
func LocalIP() string {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP.String()
}

11
src/utils/ip_test.go Normal file
View File

@ -0,0 +1,11 @@
package utils
import (
"fmt"
"testing"
)
func TestGetIP(t *testing.T) {
fmt.Println(PublicIP())
fmt.Println(LocalIP())
}