Skip to content

Commit 122d1b5

Browse files
committed
parse first/last addresses from CIDR properly
1 parent b577576 commit 122d1b5

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/CIDR.php

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ class CIDR
77
protected string $prefix;
88
protected int $length;
99

10+
// network address
1011
protected int $start;
12+
// broadcast address
1113
protected int $end;
1214

1315
/**
@@ -49,7 +51,7 @@ protected function parseOrFail(string $cidrNotation): void
4951
$prefix = intval($parts[1]);
5052

5153
if ($prefix < 0 || $prefix > 32) {
52-
throw new \InvalidArgumentException('Invalid CIDR: ' . $cidrNotation);
54+
throw new \InvalidArgumentException('Invalid CIDR prefix: ' . $cidrNotation);
5355
}
5456

5557
$start = ip2long($address);
@@ -58,14 +60,15 @@ protected function parseOrFail(string $cidrNotation): void
5860
throw new \InvalidArgumentException('Invalid IP address: ' . $address);
5961
}
6062

61-
$prefixLength = pow(2, (32 - $prefix)) - 1;
62-
$end = $start + $prefixLength;
63+
$mask = -1 << (32 - $prefix);
64+
$networkAddress = ip2long($address) & $mask;
65+
$broadcastAddress = $networkAddress | ~$mask;
6366

6467
$this->prefix = $address;
6568
$this->length = $prefix;
6669

67-
$this->start = $start;
68-
$this->end = $end;
70+
$this->start = $networkAddress;
71+
$this->end = $broadcastAddress;
6972
}
7073

7174
public function getFirstAddress(): string

0 commit comments

Comments
 (0)