Golang : How to check if IP address is in range
For security purpose, sometimes a server can only accept connection from clients that are trusted and of certain IP addresses. This tutorial will demonstrate how to use bytes.Compare() function to check to see if an incoming IP address is within the trusted range.
checkip.go
package main
import (
"net"
"bytes"
"fmt"
)
var (
// specify the range of trusted IP addresses
start = net.ParseIP("198.162.1.100")
end = net.ParseIP("198.162.1.199")
)
func checkIP(ip string) bool {
//sanity check
input := net.ParseIP(ip)
if input.To4() == nil {
fmt.Printf("%v is not a valid IPv4 address\n", input)
return false
}
if bytes.Compare(input, start) >= 0 && bytes.Compare(input, end) <= 0 {
fmt.Printf("%v is between %v and %v\n", input, start, end)
return true
}
fmt.Printf("%v is NOT between %v and %v\n", input, start, end)
return false
}
func main() {
fmt.Println(checkIP("216.14.49.185"))
fmt.Println(checkIP("1.2.3.4"))
fmt.Println(checkIP("198.162.1.102"))
fmt.Println(checkIP("1::16"))
}
Output :
216.14.49.185 is NOT between 198.162.1.100 and 198.162.1.199
false
1.2.3.4 is NOT between 198.162.1.100 and 198.162.1.199
false
198.162.1.102 is between 198.162.1.100 and 198.162.1.199
true
1::16 is not an IPv4 address
false
Reference :
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.2k Golang : Individual and total number of words counter example
+19.4k Golang : Example for DSA(Digital Signature Algorithm) package functions
+15.5k Golang : Get checkbox or extract multipart form data value example
+5.1k Golang : Issue HTTP commands to server and port example
+28.9k Golang : Get first few and last few characters from string
+15.6k Golang : How to login and logout with JWT example
+13.7k Golang : convert(cast) string to float value
+13.7k Golang : Convert spaces to tabs and back to spaces example
+7.6k Golang : Test if an input is an Armstrong number example
+9.4k Golang : Changing a RGBA image number of channels with OpenCV
+11.1k Golang : Calculate Relative Strength Index(RSI) example
+14.2k Golang : How to convert a number to words