An example of IP segment range verification in go language

Time:2021-4-21

background

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.

Solution

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

192.123.1.0 ~ 192.123.156.255

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: 192.168.1.0 ~ 192.172.3.255
IP: 192.160.0.255

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.

code

Here is the sample code:


package main

import (
 "fmt"
 "strconv"
 "strings"
)

func main() {
 ipVerifyList := "192.168.1.0-192.172.3.255"
 ip := "192.170.223.1"
 ipSlice := strings.Split(ipVerifyList, `-`)
 if len(ipSlice) < 0 {
  return
 }
 if ip2Int(ip) >= ip2Int(ipSlice[0]) && ip2Int(ip) <= ip2Int(ipSlice[1]) {
  fmt.Println("ip in iplist")
  return
 }
 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)
 return
}

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 […]