From a3f8aaa5df1f0d2fa8d644e387f9b185dea2d55a Mon Sep 17 00:00:00 2001 From: "zhangxu19830126@gmail.com" Date: Tue, 26 Dec 2017 14:07:05 +0800 Subject: [PATCH] dev: add ip adjust --- ip.go | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ server.go | 16 +++++++++- 2 files changed, 102 insertions(+), 1 deletion(-) create mode 100644 ip.go diff --git a/ip.go b/ip.go new file mode 100644 index 0000000..ce96f6d --- /dev/null +++ b/ip.go @@ -0,0 +1,87 @@ +package grpcx + +import ( + "net" + "strconv" + "strings" +) + +func intranetIP() (ips []string, err error) { + ips = make([]string, 0) + + ifaces, e := net.Interfaces() + if e != nil { + return ips, e + } + + for _, iface := range ifaces { + if iface.Flags&net.FlagUp == 0 { + continue // interface down + } + + if iface.Flags&net.FlagLoopback != 0 { + continue // loopback interface + } + + // ignore docker and warden bridge + if strings.HasPrefix(iface.Name, "docker") || strings.HasPrefix(iface.Name, "w-") { + continue + } + + addrs, e := iface.Addrs() + if e != nil { + return ips, e + } + + for _, addr := range addrs { + var ip net.IP + switch v := addr.(type) { + case *net.IPNet: + ip = v.IP + case *net.IPAddr: + ip = v.IP + } + + if ip == nil || ip.IsLoopback() { + continue + } + + ip = ip.To4() + if ip == nil { + continue // not an ipv4 address + } + + ipStr := ip.String() + if isIntranet(ipStr) { + ips = append(ips, ipStr) + } + } + } + + return ips, nil +} + +func isIntranet(ipStr string) bool { + if strings.HasPrefix(ipStr, "10.") || strings.HasPrefix(ipStr, "192.168.") { + return true + } + + if strings.HasPrefix(ipStr, "172.") { + // 172.16.0.0-172.31.255.255 + arr := strings.Split(ipStr, ".") + if len(arr) != 4 { + return false + } + + second, err := strconv.ParseInt(arr[1], 10, 64) + if err != nil { + return false + } + + if second >= 16 && second <= 31 { + return true + } + } + + return false +} diff --git a/server.go b/server.go index a346f7a..bd64193 100644 --- a/server.go +++ b/server.go @@ -1,6 +1,7 @@ package grpcx import ( + "fmt" "net" "github.com/fagongzi/log" @@ -135,7 +136,7 @@ func (s *GRPCServer) publishServices() { for _, service := range s.services { err := s.opts.publisher.Publish(service.Name, naming.Update{ Op: naming.Add, - Addr: s.addr, + Addr: adjustAddr(s.addr), Metadata: service.Metadata, }) if err != nil { @@ -146,3 +147,16 @@ func (s *GRPCServer) publishServices() { } } } + +func adjustAddr(addr string) string { + if addr[0] == ':' { + ips, err := intranetIP() + if err != nil { + log.Fatalf("get intranet ip failed, error:\n%+v", err) + } + + return fmt.Sprintf("%s%s", ips[0], addr) + } + + return addr +}