Golang : Get host name or domain name from IP address
Thought this tutorial could be a good compliment to previous tutorial on how to find network of an IP address. Basically, what this small Golang program does is to scan and try to map a given IP address to its equivalent domain/host name... a reverse of translating domain name to IP addresses.
Here you go :
package main
import (
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
)
func getHostName(host chan string, ipAddress string, n int) {
ip := ipAddress + strconv.Itoa(n)
if addr, err := net.LookupAddr(ip); err == nil {
host <- ip + " -" + addr[0]
} else {
host <- "err " + err.Error()
}
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s IP-address\n", os.Args[0])
os.Exit(1)
}
ipAddr := os.Args[1]
segments := strings.SplitAfter(ipAddr, ".")
ipAddress := segments[0] + segments[1] + segments[2]
haveHost := make(chan string)
max := 55
for counter := 0; counter < max; counter++ {
go getHostName(haveHost, ipAddress, counter)
}
count := 0
timeOut := time.After(5 * time.Second)
lookups:
for {
select {
case host := <-haveHost:
fmt.Println("host :" + host)
case <-timeOut:
fmt.Println("time out")
break lookups
}
count++
if count == max {
break
}
}
fmt.Println("Network scanned")
}
Sample output :
$ ./netinterfaces 54.255.183.119
host :54.255.183.0 -ec2-54-255-183-0.ap-southeast-1.compute.amazonaws.com.
host :54.255.183.5 -ec2-54-255-183-5.ap-southeast-1.compute.amazonaws.com.
host :54.255.183.26 -ec2-54-255-183-26.ap-southeast-1.compute.amazonaws.com.
host :54.255.183.28 -ec2-54-255-183-28.ap-southeast-1.compute.amazonaws.com.
host :54.255.183.44 -ec2-54-255-183-44.ap-southeast-1.compute.amazonaws.com.
host :54.255.183.2 -ec2-54-255-183-2.ap-southeast-1.compute.amazonaws.com.
References :
https://www.socketloop.com/tutorials/golang-find-network-of-an-ip-address
See also : Golang : Find network of an IP address
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
+32.4k Golang : Regular Expression for alphanumeric and underscore
+28.7k Golang : Get first few and last few characters from string
+29.5k Golang : Get time.Duration in year, month, week or day
+4.5k Facebook : How to place save to Facebook button on your website
+42.8k Golang : Get hardware information such as disk, memory and CPU usage
+7.1k Golang : Example of custom handler for Gorilla's Path usage.
+16.6k Golang : How to generate QR codes?
+10.3k Golang : Resolve domain name to IP4 and IP6 addresses.
+24.2k Golang : Time slice or date sort and reverse sort example
+27.1k PHP : Convert(cast) string to bigInt
+15.4k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+8.8k Golang : Handle sub domain with Gin