package main import ( "fmt" "net" ) func main() { ip := net.ParseIP("192.168.0.5") network := net.IPNet{IP: net.ParseIP("192.168.0.0"), Mask: net.CIDRMask(24, 32)} if network.Contains(ip) { fmt.Println("IP address", ip, "is in network", network) } else { fmt.Println("IP address", ip, "is not in network", network) } }
package main import ( "fmt" "net" ) func main() { ip := net.ParseIP("2001:db8::1") network := net.IPNet{IP: net.ParseIP("2001:db8::"), Mask: net.CIDRMask(64, 128)} if network.Contains(ip) { fmt.Println("IP address", ip, "is in network", network) } else { fmt.Println("IP address", ip, "is not in network", network) } }This code example is similar to the first one, but it checks an IPv6 address `2001:db8::1` against an IPv6 network prefix `2001:db8::/64`. We use the `net.ParseIP` function to create IP objects from string representations. The `Contains` method belongs to the `net` package in Go. It is part of the standard library and does not require any external packages to use.