Created
February 7, 2023 08:11
-
-
Save roundrop/050fbf6c01c6c6c62196161c9f3250f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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