An example of IP segment range verification in go language



Recently, we have made a requirement to detect whether an IP is in a number of IP segments, and do IP screening at fixed locations to meet specific business requirements.


Plan a dot decimal range discrimination

In short, it is to compare the IP addresses of the original four segments of IPv4 to see whether each segment is within the IP segment. It can be used to filter segments within 0-255 of each specific segment ~

This kind of relatively standard specific segment can realize simple filtering, but the problem comes, how to eliminate irregular continuous IP segment? As follows:

IP segment: ~

In this way, there will be problems. According to the simple segmentation comparison, it is obvious that the verification fails, but the IP still exists in the IP segment. The scheme can only distinguish the IP segments with rules under the unified segmentation.

Plan B to integer pair

IP address can be converted to integer, and IP range can be converted to integer range for troubleshooting.

In this way, you only need to convert the address within the granted range to an integer, and then you can check the IP out.


Here is the sample code:

package main

import (

func main() {
 ipVerifyList := ""
 ip := ""
 ipSlice := strings.Split(ipVerifyList, `-`)
 if len(ipSlice) < 0 {
 if ip2Int(ip) >= ip2Int(ipSlice[0]) && ip2Int(ip) <= ip2Int(ipSlice[1]) {
  fmt.Println("ip in iplist")
 fmt.Println("ip not in iplist")

func ip2Int(ip string) int64 {
 if len(ip) == 0 {
  return 0
 bits := strings.Split(ip, ".")
 if len(bits) < 4 {
  return 0
 b0 := string2Int(bits[0])
 b1 := string2Int(bits[1])
 b2 := string2Int(bits[2])
 b3 := string2Int(bits[3])

 var sum int64
 sum += int64(b0) << 24
 sum += int64(b1) << 16
 sum += int64(b2) << 8
 sum += int64(b3)

 return sum

func string2Int(in string) (out int) {
 out, _ = strconv.Atoi(in)

So far, this article about the go language implementation of IP segment range verification example is introduced here. For more relevant go IP segment range verification content, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!

Recommended Today

Looking for frustration 1.0

I believe you have a basic understanding of trust in yesterday’s article. Today we will give a complete introduction to trust. Why choose rust It’s a language that gives everyone the ability to build reliable and efficient software. You can’t write unsafe code here (unsafe block is not in the scope of discussion). Most of […]