From f3df177ba2d287bbea2a16541a7ba99e15fc191b Mon Sep 17 00:00:00 2001 From: Zack Scholl Date: Sun, 23 Sep 2018 05:27:32 -0700 Subject: [PATCH] functions to get local/public IP --- src/utils/ip.go | 39 +++++++++++++++++++++++++++++++++++++++ src/utils/ip_test.go | 11 +++++++++++ 2 files changed, 50 insertions(+) create mode 100644 src/utils/ip.go create mode 100644 src/utils/ip_test.go diff --git a/src/utils/ip.go b/src/utils/ip.go new file mode 100644 index 0000000..4142fdf --- /dev/null +++ b/src/utils/ip.go @@ -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() +} diff --git a/src/utils/ip_test.go b/src/utils/ip_test.go new file mode 100644 index 0000000..ae3fcf6 --- /dev/null +++ b/src/utils/ip_test.go @@ -0,0 +1,11 @@ +package utils + +import ( + "fmt" + "testing" +) + +func TestGetIP(t *testing.T) { + fmt.Println(PublicIP()) + fmt.Println(LocalIP()) +}