How to judge whether one network segment belongs to the subnet of another network segment in GO language
Most people do not understand the knowledge points of this article "how to judge whether a network segment belongs to the subnet of another network segment in GO language", so the editor summarizes the following contents for you. The content is detailed, the steps are clear, and it has a certain reference value. I hope you can gain something after reading this article. Let's take a look at this article entitled "how the GO language determines whether a network segment belongs to the subnet of another network segment".
1. Verify whether the network segment is legal. 1.1.The function import ("fmt"net") func IsNetWorkOk (network string) bool {_, _, err: = net.ParseCIDR (network) if err! = nil {return false} return true}
1.2 Analysis
The first step is to change split into ip and subnet mask.
The main principle is to make a judgment after it is changed to binary.
Both ipv4 and ipv6 can be verified. If you only want to verify ipv4, you can call the parseIPv4 method.
1.3 the main function runs the test func main () {ip: = "100.4.11.3 result 24" result: = IsNetWorkOk (ip) fmt.Println (result)} 2. Verify whether ip is legal 2.2.2.Analysis of function func IsIpOk (ip string) bool {address: = net.ParseIP (ip) if address = = nil {return false} return true} 2.2Function
Change dotted decimal to binary to determine whether it is legal:
2.3 the main function runs the test func main () {ip: = "100.4.11.34" result: = IsIpOk (ip) fmt.Println (result)} 3. Judge whether one is the subnet of the other. Function func ContainsCIDR (a, b * net.IPNet) bool {ones1, _: = a.Mask.Size () ones2, _: = b.Mask.Size () return ones1