Skip to content

Instantly share code, notes, and snippets.

@harshavardhana
Created April 8, 2020 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harshavardhana/dc208d81f9812e14b4497936986053d1 to your computer and use it in GitHub Desktop.
Save harshavardhana/dc208d81f9812e14b4497936986053d1 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"net"
"os"
"github.com/minio/minio-go/v6/pkg/set"
)
// getHostIP returns IP address of given host.
func getHostIP(host string) (ipList set.StringSet, err error) {
var ips []net.IP
if ips, err = net.LookupIP(host); err != nil {
return ipList, err
}
ipList = set.NewStringSet()
for _, ip := range ips {
ipList.Add(ip.String())
}
return ipList, err
}
// mustGetLocalIP4 returns IPv4 addresses of localhost. It panics on error.
func mustGetLocalIP4() (ipList set.StringSet) {
ipList = set.NewStringSet()
addrs, err := net.InterfaceAddrs()
if err != nil {
log.Fatalln(err)
}
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.To4() != nil {
ipList.Add(ip.String())
}
}
return ipList
}
// isLocalHost - checks if the given parameter
// correspond to one of the local IP of the
// current machine
func isLocalHost(host string) (bool, error) {
hostIPs, err := getHostIP(host)
if err != nil {
return false, err
}
fmt.Println("hostIPs", hostIPs)
fmt.Println("localIPs", mustGetLocalIP4())
nonInterIPV4s := mustGetLocalIP4().Intersection(hostIPs)
if nonInterIPV4s.IsEmpty() {
hostIPs = hostIPs.ApplyFunc(func(ip string) string {
if net.ParseIP(ip).IsLoopback() {
// Any loopback IP which is not 127.0.0.1
// convert it to check for intersections.
return "127.0.0.1"
}
return ip
})
nonInterIPV4s = mustGetLocalIP4().Intersection(hostIPs)
}
// If intersection of two IP sets is not empty, then the host is localhost.
return !nonInterIPV4s.IsEmpty(), nil
}
func main() {
isLocal, err := isLocalHost(os.Args[1])
if err != nil {
log.Fatalln(fmt.Errorf("%s resolution failed, %w", os.Args[1], err))
}
fmt.Println("%s resolved is it local to this server?: %s", os.Args[1], isLocal)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment