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
+8.4k Golang : Get final or effective URL with Request.URL example
+23.3k Golang : simulate tail -f or read last line from log file example
+36.9k Golang : Display float in 2 decimal points and rounding up or down
+5.6k How to check with curl if my website or the asset is gzipped ?
+7.4k Golang : Dealing with postal or zip code example
+33.2k Golang : How to check if a date is within certain range?
+5k Golang : A program that contain another program and executes it during run-time
+6.2k Golang : How to verify input is rune?
+7.4k CloudFlare : Another way to get visitor's real IP address
+5.6k Golang : fmt.Println prints out empty data from struct
+10.9k Android Studio : Simple input textbox and intercept key example
+14.4k Golang : Convert IP version 6 address to integer or decimal number