Skip to content

Instantly share code, notes, and snippets.

@roundrop
Created February 7, 2023 08:11
Show Gist options
  • Save roundrop/050fbf6c01c6c6c62196161c9f3250f0 to your computer and use it in GitHub Desktop.
Save roundrop/050fbf6c01c6c6c62196161c9f3250f0 to your computer and use it in GitHub Desktop.
import java.net.InetAddress
object CIDRChecker {
def isInRange(cidrs: Array[String], address: String): Boolean = {
cidrs.exists { cidr =>
if (!cidr.contains("/")) {
InetAddress.getByName(cidr).getHostAddress == InetAddress.getByName(address).getHostAddress
} else {
val Array(cidrAddress, cidrMask) = cidr.split("/")
val cidrInt = InetAddress.getByName(cidrAddress).getAddress.zipWithIndex.map { case (b, i) => (b & 0xff) << (8 * (3 - i)) }.sum
val mask = ~((1 << (32 - cidrMask.toInt)) - 1)
val addressInt = InetAddress.getByName(address).getAddress.zipWithIndex.map { case (b, i) => (b & 0xff) << (8 * (3 - i)) }.sum
(addressInt & mask) == cidrInt
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment