diff --git a/shared/src/main/scala/com/comcast/ip4s/Cidr.scala b/shared/src/main/scala/com/comcast/ip4s/Cidr.scala index 9112e9e..0f01075 100644 --- a/shared/src/main/scala/com/comcast/ip4s/Cidr.scala +++ b/shared/src/main/scala/com/comcast/ip4s/Cidr.scala @@ -16,7 +16,6 @@ package com.comcast.ip4s -import scala.util.Try import scala.util.hashing.MurmurHash3 import cats.{Order, Show} @@ -149,7 +148,8 @@ object Cidr { case CidrPattern(addrStr, prefixBitsStr) => for { addr <- parseAddress(addrStr) - prefixBits <- Try(prefixBitsStr.toInt).toOption + maxPrefixBits = addr.fold(_ => 32, _ => 128) + prefixBits <- prefixBitsStr.toIntOption if prefixBits >= 0 && prefixBits <= maxPrefixBits } yield Cidr(addr, prefixBits) case _ => None } diff --git a/test-kit/shared/src/test/scala/com/comcast/ip4s/CidrTest.scala b/test-kit/shared/src/test/scala/com/comcast/ip4s/CidrTest.scala index 5eccd1d..49dc9ed 100644 --- a/test-kit/shared/src/test/scala/com/comcast/ip4s/CidrTest.scala +++ b/test-kit/shared/src/test/scala/com/comcast/ip4s/CidrTest.scala @@ -33,4 +33,12 @@ class CidrTest extends BaseTestSuite { assertEquals(Cidr.fromIpAndMask(ip, mask), Cidr(ip, prefixBits)) } } + + property("parsing from string: only masks with a valid length return a CIDR") { + forAll { (ip: IpAddress, prefixBits: Int) => + val cidr = Cidr.fromString(s"$ip/$prefixBits") + val max = ip.fold(_ => 32, _ => 128) + assertEquals(cidr.isDefined, (prefixBits <= max && prefixBits >= 0)) + } + } }