github.com/decred/politeia@v1.4.0/util/fqdn.go (about)

     1  // Copyright (c) 2017-2019 The Decred developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package util
     6  
     7  import (
     8  	"net"
     9  	"os"
    10  	"strings"
    11  )
    12  
    13  // FQDN returns the fully qualified domain name of the machine it is running
    14  // on.
    15  func FQDN() string {
    16  	hostname, err := os.Hostname()
    17  	if err != nil {
    18  		return "localhost"
    19  	}
    20  
    21  	addrs, err := net.LookupIP(hostname)
    22  	if err != nil {
    23  		return hostname
    24  	}
    25  
    26  	for _, addr := range addrs {
    27  		if ipv4 := addr.To4(); ipv4 != nil {
    28  			ip, err := ipv4.MarshalText()
    29  			if err != nil {
    30  				return hostname
    31  			}
    32  			hosts, err := net.LookupAddr(string(ip))
    33  			if err != nil || len(hosts) == 0 {
    34  				return hostname
    35  			}
    36  			fqdn := hosts[0]
    37  			return strings.TrimSuffix(fqdn, ".")
    38  		}
    39  	}
    40  
    41  	return hostname
    42  }