2019-06-02 00:24:26 -05:00
|
|
|
package main
|
|
|
|
|
2019-06-02 22:07:13 -05:00
|
|
|
import "net"
|
|
|
|
import "os"
|
|
|
|
import "strings"
|
|
|
|
import "log"
|
2019-06-02 00:24:26 -05:00
|
|
|
|
|
|
|
// Get Fully Qualified Domain Name
|
|
|
|
// returns "unknown" or hostanme in case of error
|
2019-06-02 22:07:13 -05:00
|
|
|
func fqdnGet() string {
|
|
|
|
log.Println("fqdnGet() START")
|
2019-06-02 00:24:26 -05:00
|
|
|
hostname, err := os.Hostname()
|
|
|
|
if err != nil {
|
|
|
|
return "unknown"
|
|
|
|
}
|
|
|
|
|
2019-06-02 22:07:13 -05:00
|
|
|
log.Println("\tfqdnGet() net.LookupIP(hostname) hostname =", hostname)
|
2019-06-02 00:24:26 -05:00
|
|
|
addrs, err := net.LookupIP(hostname)
|
|
|
|
if err != nil {
|
2019-06-02 22:07:13 -05:00
|
|
|
log.Println("\tfqdnGet() net.LookupIP(hostname) err =", err)
|
2019-06-02 00:24:26 -05:00
|
|
|
return hostname
|
|
|
|
}
|
|
|
|
|
2019-06-02 22:07:13 -05:00
|
|
|
log.Println("\tfqdnGet() range addrs")
|
2019-06-02 00:24:26 -05:00
|
|
|
for _, addr := range addrs {
|
2019-06-02 22:07:13 -05:00
|
|
|
log.Println("\tfqdnGet() addr = ", addr)
|
2019-06-02 00:24:26 -05:00
|
|
|
if ipv4 := addr.To4(); ipv4 != nil {
|
|
|
|
ip, err := ipv4.MarshalText()
|
2019-06-02 22:07:13 -05:00
|
|
|
log.Println("\tfqdnGet() ip = ", string(ip))
|
2019-06-02 00:24:26 -05:00
|
|
|
if err != nil {
|
|
|
|
return hostname
|
|
|
|
}
|
2019-06-02 22:07:13 -05:00
|
|
|
log.Println("\tfqdnGet() net.LookupAddr = ", string(ip))
|
2019-06-02 00:24:26 -05:00
|
|
|
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
|
|
|
|
}
|