Golang : Reverse IP address for reverse DNS lookup example
Problem:
You need to reverse a given IPv4 address into a DNS reverse record form to perform reverse DNS lookup or simply want to read an IP address backwards. How to do that?
Solution:
Break the given IP address into a slice and reverse the octets sequence with a for loop.
Edit: The previous solution used the sort
package. However, it will sort the IP during reverse sorting(which is working as intended) ... instead of just reversing.
10.106
to 106.10
and this will introduce hard to trace bug.
Before : 106.10.138.240
After : 240.138.106.10 <-- notice the position of 106 octet swapped with 10 octet
The solution below will just reverse the octets position and no sort.
Here you go!
package main
import (
"fmt"
"net"
"strings"
)
func ReverseIPAddress(ip net.IP) string {
if ip.To4() != nil {
// split into slice by dot .
addressSlice := strings.Split(ip.String(), ".")
reverseSlice := []string{}
for i := range addressSlice {
octet := addressSlice[len(addressSlice)-1-i]
reverseSlice = append(reverseSlice, octet)
}
// sanity check
//fmt.Println(reverseSlice)
return strings.Join(reverseSlice, ".")
} else {
panic("invalid IPv4 address")
}
}
func main() {
ipAddress := net.ParseIP("106.10.138.240")
fmt.Println("Before : ", ipAddress.To4())
reverseIpAddress := ReverseIPAddress(ipAddress)
fmt.Println("After : ", reverseIpAddress)
// convert to DNS reverse record form
reverseIpAddress = reverseIpAddress + ".in-addr.arpa"
fmt.Println("With in-addr.arpa : ", reverseIpAddress)
}
Output:
Before : 106.10.138.240
After : 240.138.10.106
With in-addr.arpa : 240.138.10.106.in-addr.arpa
References:
https://golang.org/pkg/sort/#StringSlice
http://unix.stackexchange.com/questions/132779/how-to-read-an-ip-address-backwards
See also : Golang : Check if IP address is version 4 or 6
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.7k Golang : Get all countries phone codes
+11.2k Golang : Simple file scaning and remove virus example
+7k Golang : File system scanning
+9.4k Golang : Load ASN1 encoded DSA public key PEM file example
+18.6k Golang : Check whether a network interface is up on your machine
+18.7k Golang : Get host name or domain name from IP address
+16.2k Golang : File path independent of Operating System
+21.6k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+7.6k Golang : Gomobile init produce "iphoneos" cannot be located error
+10.7k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+12.9k Golang : Date and Time formatting
+5.8k Javascript : Get operating system and browser information