// Use freely with source code level attribution (a comment in the source code linking to this page is fine) package foo import ( "fmt" "net" "os" "strings" ) // GetFQDN gets a fully qualified domain name for a given host (use empty string for the local host) // // GetFQDN follows the same logic as Python's `socket.getfqdn([name])` // (https://docs.python.org/3.5/library/socket.html#socket.getfqdn) // in selecting the first name that contains a period. func GetFQDN(hostname string) string { var err error if hostname == "" { hostname, err = os.Hostname() if err != nil { panic("cannot look up hostname") } } ips, err := net.LookupIP(hostname) if err != nil { return hostname } var results = make([]string, 0) for _, ip := range ips { hosts, err := net.LookupAddr(ip.String()) if err != nil { continue } for _, host := range hosts { results = append(results, fmt.Sprintf("%s: %s", ip.String(), host)) if -1 != strings.LastIndexByte(host, '.') { return strings.TrimSuffix(host, ".") } } } return hostname }