From 69169c158d7643425333dc4df5511b7207c115e6 Mon Sep 17 00:00:00 2001 From: Yaxian Date: Wed, 20 Oct 2021 20:24:45 +0800 Subject: [PATCH] feat: optimise get server ip --- src/common/config/config.go | 15 +++++++++++++-- src/utils/get_server_ip.go | 23 +++++++---------------- src/utils/get_server_ip_test.go | 11 +++++++++++ 3 files changed, 31 insertions(+), 18 deletions(-) create mode 100644 src/utils/get_server_ip_test.go diff --git a/src/common/config/config.go b/src/common/config/config.go index faf75a5b8..93b17a81f 100644 --- a/src/common/config/config.go +++ b/src/common/config/config.go @@ -1,8 +1,17 @@ package config import ( - "gopkg.in/yaml.v3" "io/ioutil" + "path/filepath" + "runtime" + + "gopkg.in/yaml.v3" +) + +var ( + _, b, _, _ = runtime.Caller(0) + // Root folder of this project + Root = filepath.Join(filepath.Dir(b), "../../..") ) var Config config @@ -147,7 +156,9 @@ type config struct { } func init() { - bytes, err := ioutil.ReadFile("../config/config.yaml") + // if we cd Open-IM-Server/src/utils and run go test + // it will panic cannot find config/config.yaml + bytes, err := ioutil.ReadFile(Root + "/config/config.yaml") if err != nil { panic(err) return diff --git a/src/utils/get_server_ip.go b/src/utils/get_server_ip.go index 21092ffa1..ec5824cb8 100644 --- a/src/utils/get_server_ip.go +++ b/src/utils/get_server_ip.go @@ -13,23 +13,14 @@ func init() { ServerIP = config.Config.ServerIP return } - //fixme Get the ip of the local network card - netInterfaces, err := net.Interfaces() + + // see https://gist.github.com/jniltinho/9787946#gistcomment-3019898 + conn, err := net.Dial("udp", "8.8.8.8:80") if err != nil { panic(err) } - for i := 0; i < len(netInterfaces); i++ { - //Exclude useless network cards by judging the net.flag Up flag - if (netInterfaces[i].Flags & net.FlagUp) != 0 { - address, _ := netInterfaces[i].Addrs() - for _, addr := range address { - if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() { - if ipNet.IP.To4() != nil { - ServerIP = ipNet.IP.String() - return - } - } - } - } - } + + defer conn.Close() + localAddr := conn.LocalAddr().(*net.UDPAddr) + ServerIP = localAddr.IP.String() } diff --git a/src/utils/get_server_ip_test.go b/src/utils/get_server_ip_test.go new file mode 100644 index 000000000..161037983 --- /dev/null +++ b/src/utils/get_server_ip_test.go @@ -0,0 +1,11 @@ +package utils + +import ( + "testing" +) + +func TestServerIP(t *testing.T) { + if ServerIP == "" { + t.Fail() + } +}