From 607cd5468f53f7904421d11a8fc3ae6d3490069b Mon Sep 17 00:00:00 2001 From: Mzack9999 Date: Fri, 27 Jan 2023 13:09:00 +0100 Subject: [PATCH] adding reverse ptr --- ip/iputil.go | 20 ++++++++++++++++++++ ip/iputil_test.go | 8 ++++++++ 2 files changed, 28 insertions(+) diff --git a/ip/iputil.go b/ip/iputil.go index 3e09814..ed7b147 100644 --- a/ip/iputil.go +++ b/ip/iputil.go @@ -315,3 +315,23 @@ func GetBindableAddress(port int, ips ...string) (string, error) { return "", errs } + +// ToFQDN performs a reverse PTR using default system resolvers +func ToFQDN(target string) ([]string, error) { + if !IsIP(target) { + return []string{target}, fmt.Errorf("%s is not an IP", target) + } + names, err := net.LookupAddr(target) + if err != nil { + return nil, err + } + if len(names) == 0 { + return names, fmt.Errorf("no names found for ip: %s", target) + } + + for i, name := range names { + names[i] = stringsutil.TrimSuffixAny(name, ".") + } + + return names, nil +} diff --git a/ip/iputil_test.go b/ip/iputil_test.go index ff3ba22..cc93493 100644 --- a/ip/iputil_test.go +++ b/ip/iputil_test.go @@ -108,3 +108,11 @@ func TestWhatsMyIP(t *testing.T) { _, err := WhatsMyIP() require.Nil(t, err, "couldn't retrieve ip") } + +func TestToFQDN(t *testing.T) { + // we can't compare the ip with local interfaces as it might be the external gateway one + // so we just verify we can contact the api endpoint + fqdns, err := ToFQDN("1.1.1.1") + require.Nil(t, err, "couldn't retrieve ip") + require.NotNil(t, fqdns) +}