44 lines
1.0 KiB
Go
44 lines
1.0 KiB
Go
package main
|
|
|
|
import "net"
|
|
import "os"
|
|
import "strings"
|
|
import "log"
|
|
|
|
// Get Fully Qualified Domain Name
|
|
// returns "unknown" or hostanme in case of error
|
|
func fqdnGet() string {
|
|
log.Println("fqdnGet() START")
|
|
hostname, err := os.Hostname()
|
|
if err != nil {
|
|
return "unknown"
|
|
}
|
|
|
|
log.Println("\tfqdnGet() net.LookupIP(hostname) hostname =", hostname)
|
|
addrs, err := net.LookupIP(hostname)
|
|
if err != nil {
|
|
log.Println("\tfqdnGet() net.LookupIP(hostname) err =", err)
|
|
return hostname
|
|
}
|
|
|
|
log.Println("\tfqdnGet() range addrs")
|
|
for _, addr := range addrs {
|
|
log.Println("\tfqdnGet() addr = ", addr)
|
|
if ipv4 := addr.To4(); ipv4 != nil {
|
|
ip, err := ipv4.MarshalText()
|
|
log.Println("\tfqdnGet() ip = ", string(ip))
|
|
if err != nil {
|
|
return hostname
|
|
}
|
|
log.Println("\tfqdnGet() net.LookupAddr = ", string(ip))
|
|
hosts, err := net.LookupAddr(string(ip))
|
|
if err != nil || len(hosts) == 0 {
|
|
return hostname
|
|
}
|
|
fqdn := hosts[0]
|
|
return strings.TrimSuffix(fqdn, ".") // return fqdn without trailing dot
|
|
}
|
|
}
|
|
return hostname
|
|
}
|