5 changed files with 94 additions and 1 deletions
@ -0,0 +1,35 @@ |
|||||||
|
package utils |
||||||
|
|
||||||
|
import ( |
||||||
|
"net" |
||||||
|
|
||||||
|
log "github.com/sirupsen/logrus" |
||||||
|
) |
||||||
|
|
||||||
|
// IsHostnameInternal will attempt to determine if the hostname is internal to
|
||||||
|
// this server's network or is the loopback address.
|
||||||
|
func IsHostnameInternal(hostname string) bool { |
||||||
|
// If this is already an IP address don't try to resolve it
|
||||||
|
if ip := net.ParseIP(hostname); ip != nil { |
||||||
|
return isIPAddressInternal(ip) |
||||||
|
} |
||||||
|
|
||||||
|
ips, err := net.LookupIP(hostname) |
||||||
|
if err != nil { |
||||||
|
// Default to false if we can't resolve the hostname.
|
||||||
|
log.Debugln("Unable to resolve hostname:", hostname) |
||||||
|
return false |
||||||
|
} |
||||||
|
|
||||||
|
for _, ip := range ips { |
||||||
|
if isIPAddressInternal(ip) { |
||||||
|
return true |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
return false |
||||||
|
} |
||||||
|
|
||||||
|
func isIPAddressInternal(ip net.IP) bool { |
||||||
|
return ip.IsLoopback() || ip.IsPrivate() |
||||||
|
} |
@ -0,0 +1,32 @@ |
|||||||
|
package utils |
||||||
|
|
||||||
|
import ( |
||||||
|
"net" |
||||||
|
"testing" |
||||||
|
) |
||||||
|
|
||||||
|
func TestIPAddressInternal(t *testing.T) { |
||||||
|
internalLoopbackHost := "localhost" |
||||||
|
internalLoopbackHostTest := IsHostnameInternal(internalLoopbackHost) |
||||||
|
if !internalLoopbackHostTest { |
||||||
|
t.Errorf("IsHostnameInternal(%s) = %v; want true", internalLoopbackHost, internalLoopbackHostTest) |
||||||
|
} |
||||||
|
|
||||||
|
internalLoopbackIP := net.ParseIP("127.0.0.1") |
||||||
|
internalLoopbackIPTest := isIPAddressInternal(internalLoopbackIP) |
||||||
|
if !internalLoopbackIPTest { |
||||||
|
t.Errorf("isIPAddressInternal(%s) = %v; want true", internalLoopbackIP, internalLoopbackIPTest) |
||||||
|
} |
||||||
|
|
||||||
|
externalHost := "example.com" |
||||||
|
externalHostTest := IsHostnameInternal(externalHost) |
||||||
|
if externalHostTest { |
||||||
|
t.Errorf("IsHostnameInternal(%s) = %v; want false", externalHost, externalHostTest) |
||||||
|
} |
||||||
|
|
||||||
|
externalIP := net.ParseIP("93.184.216.34") |
||||||
|
externalIPTest := isIPAddressInternal(externalIP) |
||||||
|
if externalIPTest { |
||||||
|
t.Errorf("isIPAddressInternal(%s) = %v; want false", externalIP, externalIPTest) |
||||||
|
} |
||||||
|
} |
Loading…
Reference in new issue