aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/gethostip.go
blob: ea2df83f4c9c96ec117300e9ca41e1561451bf73 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// +build dragonfly freebsd linux nacl netbsd openbsd solaris darwin

package main

import (
	"net"
)

// 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"
}