Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented a more reliable way for detecting the internal ip. #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 17 additions & 13 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,24 +70,28 @@ func Register(instance, service, domain string, port int, text []string, iface *
}
entry.HostName = fmt.Sprintf("%s.", trimDot(entry.HostName))

addrs, err := net.LookupIP(entry.HostName)

// GetLocalIP returns the non loopback local IP of the host
iaddrs, err := net.InterfaceAddrs()
if err != nil {
// Try appending the host domain suffix and lookup again
// (required for Linux-based hosts)
tmpHostName := fmt.Sprintf("%s%s.", entry.HostName, entry.Domain)
addrs, err = net.LookupIP(tmpHostName)
if err != nil {
return nil, fmt.Errorf("Could not determine host IP addresses for %s", entry.HostName)
}
return nil, err
}
for i := 0; i < len(addrs); i++ {
if ipv4 := addrs[i].To4(); ipv4 != nil {
entry.AddrIPv4 = addrs[i]
} else if ipv6 := addrs[i].To16(); ipv6 != nil {
entry.AddrIPv6 = addrs[i]

for _, address := range iaddrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One issue here is that it includes ipv6 link-local ips. These can be ignored using && !ipnet.IP.IsLinkLocalUnicast()

if ipnet.IP.To4() != nil {
entry.AddrIPv4 = ipnet.IP
} else if ipnet.IP.To16() != nil {
entry.AddrIPv6 = ipnet.IP
}
}
}

if entry.AddrIPv4 == nil && entry.AddrIPv6 == nil {
return nil, fmt.Errorf("Could not determine host IP addresses")
}

s, err := newServer(iface)
if err != nil {
return nil, err
Expand Down