Created
January 23, 2020 07:25
-
-
Save golightlyb/0d6a0270b0cff882d373dfc6704c5e34 to your computer and use it in GitHub Desktop.
Go / golang: GetFQDN gets a fully qualified domain name for a given host
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment