feat: optimise get server ip (#20)

* feat: optimise get server ip

* feat: test ServerIP
pull/24/head
Yaxian 3 years ago committed by GitHub
parent 7caf5a0df9
commit c8155553b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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,14 +156,14 @@ 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
}
if err = yaml.Unmarshal(bytes, &Config); err != nil {
panic(err)
return
}
}

@ -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()
}

@ -0,0 +1,12 @@
package utils
import (
"net"
"testing"
)
func TestServerIP(t *testing.T) {
if net.ParseIP(ServerIP) == nil {
t.Fail()
}
}
Loading…
Cancel
Save