From 3156765985f2e7ad7b533c893de9d5ce56aab0ee Mon Sep 17 00:00:00 2001 From: Mitchell Riedstra Date: Wed, 11 Aug 2021 23:44:53 -0400 Subject: Add a Windows specific function to scrape the route table for the IP address from the default route. --- cmd/web/gethostip.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 cmd/web/gethostip.go (limited to 'cmd/web/gethostip.go') diff --git a/cmd/web/gethostip.go b/cmd/web/gethostip.go new file mode 100644 index 0000000..3788ac1 --- /dev/null +++ b/cmd/web/gethostip.go @@ -0,0 +1,36 @@ +// +build dragonfly freebsd linux nacl netbsd openbsd solaris darwin + +package main + +// GetHostIP attempts to guess the IP address of the current machine and +// returns that. Simply bails at the first non sane looking IP and returns it. +// Not ideal but it should work well enough most of the time +func GetHostIP() string { + iFaces, err := net.Interfaces() + if err != nil { + return "127.0.0.1" + } + + // RFC 3927 + _, ipv4LinkLocal, _ := net.ParseCIDR("169.254.0.0/16") + + for _, iFace := range iFaces { + addrs, err := iFace.Addrs() + if err != nil { + continue + } + + for _, a := range addrs { + n, ok := a.(*net.IPNet) + if !ok { + continue + } + + if n.IP.To4() != nil && !n.IP.IsLoopback() && !ipv4LinkLocal.Contains(n.IP.To4()) { + return n.IP.String() + } + } + } + + return "127.0.0.1" +} -- cgit v1.2.3