commit
97e5d9f610
@ -1,26 +1,28 @@
|
|||||||
package utils
|
package utils
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"Open_IM/pkg/common/config"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
)
|
)
|
||||||
|
|
||||||
var ServerIP = ""
|
var ServerIP = ""
|
||||||
|
|
||||||
func init() {
|
func GetLocalIP() (string, error) {
|
||||||
//fixme In the configuration file, ip takes precedence, if not, get the valid network card ip of the machine
|
addrs, err := net.InterfaceAddrs()
|
||||||
if config.Config.ServerIP != "" {
|
if err != nil {
|
||||||
ServerIP = config.Config.ServerIP
|
|
||||||
return
|
return "", err
|
||||||
}
|
}
|
||||||
|
for _, address := range addrs {
|
||||||
|
|
||||||
// see https://gist.github.com/jniltinho/9787946#gistcomment-3019898
|
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
|
||||||
conn, err := net.Dial("udp", "8.8.8.8:80")
|
if ipnet.IP.To4() != nil {
|
||||||
if err != nil {
|
fmt.Println(ipnet.IP.String())
|
||||||
panic(err.Error())
|
return ipnet.IP.String(), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
defer conn.Close()
|
return "", errors.New("no ip")
|
||||||
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
|
||||||
ServerIP = localAddr.IP.String()
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in new issue