You can Go
use net
the package in the language to determine IP
whether is within a given network segment. Specific steps are as follows:
- Use
net.ParseCIDR()
the method to parse the given network segment and returnIP
the address and subnet mask of the network segment. - Use
net.ParseIP()
the method to parseIP
the address to be judged. - Use
net.IPNet.Contains()
the method to judgeIP
whether the address to be judged is in the network segment.
Here is a sample code:
package main
import (
"fmt"
"net"
)
func main() {
ip := net.ParseIP("192.168.0.1")
_, ipNet, _ := net.ParseCIDR("192.168.0.0/24")
if ipNet.Contains(ip) {
fmt.Println("IP is in subnet")
} else {
fmt.Println("IP is not in subnet")
}
}
In this example, IP
the address 192.168.0.1
, and the network segment to be judged is parsed 192.168.0.0/24
, and then net.IPNet.Contains()
the method to judge IP
whether the address is in the network segment. If it is in the network segment, output IP is in subnet
, otherwise output IP is not in subnet
.
Tips: I have to say that Golang
the code looks really concise. Although there are a lot of actual business codes when writing return
, hahaha, it is very comfortable to write.
Personal blog: Roc's Blog