Skip to content

Instantly share code, notes, and snippets.

@fionera
Last active October 25, 2021 19:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fionera/6b7dfeb6295db7a7c83593430d1fdd52 to your computer and use it in GitHub Desktop.
Save fionera/6b7dfeb6295db7a7c83593430d1fdd52 to your computer and use it in GitHub Desktop.
Reverse IP Converter in Go

Reverse IP

Converts an IP to the reverse DNS Style:

		{
			name:   "v4",
			IP:     net.ParseIP("1.2.3.4"),
			output: "4.3.2.1",
		},
		{
			name:   "v4",
			IP:     net.ParseIP("255.255.255.255"),
			output: "255.255.255.255",
		},
		{
			name:   "v6",
			IP:     net.ParseIP("2001::"),
			output: "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.0.0.2",
		},
=== RUN   Test/v4
    test_scratch_9_test.go:43: 22515540	        49.38 ns/op
    --- PASS: Test/v4 (2.15s)
=== RUN   Test/v4#01
    test_scratch_9_test.go:43: 17212569	        71.24 ns/op
    --- PASS: Test/v4#01 (1.30s)
=== RUN   Test/v6
    test_scratch_9_test.go:43: 23410729	        50.83 ns/op
    --- PASS: Test/v6 (1.24s)
PASS
func reverseaddr(ip net.IP) string {
const hexDigit = "0123456789abcdef"
buf := make([]byte, 0, len(ip)*4)
if v4 := ip.To4(); v4 != nil {
for i := len(v4) - 1; i >= 0; i-- {
buf = append(buf, '.')
buf = strconv.AppendUint(buf, uint64(v4[i]), 10)
}
} else {
for i := len(ip) - 1; i >= 0; i-- {
buf = append(buf, '.', hexDigit[ip[i]&0xF], '.', hexDigit[ip[i]>>4])
}
}
return b2s(buf[1:])
}
func b2s(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment