1. package common
  2. import (
  3. "net"
  4. "errors"
  5. )
  6. func GetIntranceIp()(string ,error) {
  7. addrs,err:=net.InterfaceAddrs()
  8. if err !=nil {
  9. return "",err
  10. }
  11. for _,address:= range addrs{
  12. //检查Ip地址判断是否回环地址
  13. if ipnet,ok:=address.(*net.IPNet);ok&&!ipnet.IP.IsLoopback(){
  14. if ipnet.IP.To4() != nil {
  15. return ipnet.IP.String(),nil
  16. }
  17. }
  18. }
  19. return "",errors.New("获取地址异常")
  20. }

Open_IM中

  1. package utils
  2. import (
  3. "Open_IM/pkg/common/config"
  4. "net"
  5. )
  6. var ServerIP = ""
  7. func init() {
  8. //fixme In the configuration file, ip takes precedence, if not, get the valid network card ip of the machine
  9. if config.Config.ServerIP != "" {
  10. ServerIP = config.Config.ServerIP
  11. return
  12. }
  13. // see https://gist.github.com/jniltinho/9787946#gistcomment-3019898
  14. conn, err := net.Dial("udp", "8.8.8.8:80")
  15. if err != nil {
  16. panic(err.Error())
  17. }
  18. defer conn.Close()
  19. localAddr := conn.LocalAddr().(*net.UDPAddr)
  20. ServerIP = localAddr.IP.String()
  21. }