Golang - check if IP address is in a network
The Go net package includes the following functions:
- ParseCIDR: takes a string representing an IP/mask and returns an IP and an IPNet
- IPNet.Contains: checks whether an IP is in a network
This should cover your needs.
Based on Zoyd's feedback...
https://play.golang.org/p/wdv2sPetmt
package main
import (
"fmt"
"net"
)
func main() {
A := "172.17.0.0/16"
B := "172.17.0.2/16"
ipA,ipnetA,_ := net.ParseCIDR(A)
ipB,ipnetB,_ := net.ParseCIDR(B)
fmt.Println("Network address A: ", A)
fmt.Println("IP address B: ", B)
fmt.Println("ipA : ", ipA)
fmt.Println("ipnetA : ", ipnetA)
fmt.Println("ipB : ", ipB)
fmt.Println("ipnetB : ", ipnetB)
fmt.Printf("\nDoes A (%s) contain: B (%s)?\n", ipnetA, ipB)
if ipnetA.Contains(ipB) {
fmt.Println("yes")
} else {
fmt.Println("no")
}
}
Based on tgogos's answer:
package main
import (
"fmt"
"net"
)
func main() {
A := "172.17.0.0/16"
B := "172.17.0.2"
_, ipnetA, _ := net.ParseCIDR(A)
ipB := net.ParseIP(B)
fmt.Printf("\nDoes A (%s) contain: B (%s)?\n", ipnetA, ipB)
if ipnetA.Contains(ipB) {
fmt.Println("yes")
} else {
fmt.Println("no")
}
}