Skip to content

Instantly share code, notes, and snippets.

@trajber
Last active July 20, 2023 08:11
Show Gist options
  • Save trajber/7cb6abd66d39662526df to your computer and use it in GitHub Desktop.
Save trajber/7cb6abd66d39662526df to your computer and use it in GitHub Desktop.
Reverse IP in Go
package main
import (
"fmt"
"net"
"os"
)
const hexDigit = "0123456789abcdef"
func main() {
reverse, err := reverseaddr(os.Args[1])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(reverse)
}
func reverseaddr(addr string) (arpa string, err error) {
ip := net.ParseIP(addr)
if ip == nil {
return "", &net.DNSError{Err: "unrecognized address", Name: addr}
}
if ip.To4() != nil {
return uitoa(uint(ip[15])) + "." + uitoa(uint(ip[14])) + "." + uitoa(uint(ip[13])) + "." + uitoa(uint(ip[12])) + ".in-addr.arpa.", nil
}
// Must be IPv6
buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
// Add it, in reverse, to the buffer
for i := len(ip) - 1; i >= 0; i-- {
v := ip[i]
buf = append(buf, hexDigit[v&0xF])
buf = append(buf, '.')
buf = append(buf, hexDigit[v>>4])
buf = append(buf, '.')
}
// Append "ip6.arpa." and return (buf already has the final .)
buf = append(buf, "ip6.arpa."...)
return string(buf), nil
}
// Convert unsigned integer to decimal string.
func uitoa(val uint) string {
if val == 0 { // avoid string allocation
return "0"
}
var buf [20]byte // big enough for 64bit value base 10
i := len(buf) - 1
for val >= 10 {
q := val / 10
buf[i] = byte('0' + val - q*10)
i--
val = q
}
// val < 10
buf[i] = byte('0' + val)
return string(buf[i:])
}
@rizalgowandy
Copy link

Thank you, this is great 💯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment