Golang : Find network of an IP address
We will learn how to use Golang's net
package to find out the network behind an IP address. It is fairly trivial to do so with Go and below is the source code.
findnetwork.go
package main
import (
"fmt"
"net"
"os"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s hostname\n", os.Args[0])
os.Exit(1)
}
hostname := os.Args[1]
IPAddr, err := net.ResolveIPAddr("ip", hostname)
if err != nil {
fmt.Println("Error in resolving IP")
os.Exit(1)
}
addr := net.ParseIP(IPAddr.String())
if addr == nil {
fmt.Println("Invalid address")
os.Exit(1)
}
mask := addr.DefaultMask()
network := addr.Mask(mask)
fmt.Printf("Address : %s \n Network : %s \n", addr.String(), network.String())
}
Sample output :
localhost:~ admin$ ./findnetwork www.nytimes.com
Address : 170.149.172.130
Network : 170.149.0.0
localhost:~ admin$ ./findnetwork www.techcrunch.com
Address : 192.0.83.250
Network : 192.0.83.0
localhost:~ admin$ ./findnetwork www.google.com
Address : 74.125.130.104
Network : 74.0.0.0
localhost:~ admin$ ./findnetwork www.yahoo.com
Address : 106.10.139.246
Network : 106.0.0.0
Reference :
See also : Get client IP Address in Go
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
+12.9k Elastic Search : Mapping date format and sort by date
+5.7k Golang : Muxing with Martini example
+46.2k Golang : How to convert JSON string to map and slice
+18.5k Golang : Append content to a file
+10.8k Golang : Print UTF-8 fonts on image example
+8k Golang : Generate random Chinese, Japanese, Korean and other runes
+12.7k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+5.1k Golang : Get missing location after unmarshal binary and gob decode time.
+8.9k Golang : Get current, epoch time and display by year, month and day
+7.4k Golang : Convert word to its plural form example
+5.1k Golang : Extract XML attribute data with attr field tag example
+3.5k Javascript : How to show different content with noscript?