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.


 package main

 import (

 var (
 // specify the range of trusted IP addresses
 start = net.ParseIP("")
 end = net.ParseIP("")

 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() {


Output : is NOT between and

false is NOT between and

false is between and


1::16 is not an IPv4 address


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.