Skip to content

Commit

Permalink
dev: add ip adjust
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangxu19830126 committed Dec 26, 2017
1 parent 999ad77 commit a3f8aaa
Show file tree
Hide file tree
Showing 2 changed files with 102 additions and 1 deletion.
87 changes: 87 additions & 0 deletions ip.go
Original file line number Diff line number Diff line change
@@ -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
}
16 changes: 15 additions & 1 deletion server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package grpcx

import (
"fmt"
"net"

"github.com/fagongzi/log"
Expand Down Expand Up @@ -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 {
Expand All @@ -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
}

0 comments on commit a3f8aaa

Please sign in to comment.