Validate an IPv4 address deliberately
Write a strict dotted-decimal IPv4 parser that returns a reusable numeric address.
An input contract is stricter than a convenient parser
Our function accepts exactly four ASCII decimal octets separated by dots. Each octet is 0–255. Except for the single digit 0, leading zeros are rejected. Reject whitespace, signs, hexadecimal, shortened forms, and IPv6. Do not silently trim the input.
.NET IPAddress parsing accepts some historical IPv4 forms such as shortened addresses. That is useful in some contexts, but it is broader than this inventory contract. Validate the complete string before converting its parts.
'192.0.2.10'.Split('.') | ForEach-Object { [int]$_ }
Use [0-9] for ASCII digits. Regex \A and \z anchor the whole input; $ can match before a final newline. A shape check still needs the numeric 255 limit.
Build a value without signed overflow
Treat the first octet as the most significant byte. Starting at zero, multiply by 256 and add each octet. Store the result in [uint64] so the full range 0 through 4,294,967,295 fits safely.
Return only that number. Throw on invalid input; emitting an error string as if it were a numeric address would corrupt later comparisons. The next lesson supplies this parser so you can focus on subnet logic.
Go deeper
'192.0.2.10'.Split('.') | ForEach-Object { [int]$_ }
Put it into practice.
Define ConvertTo-IPv4Number -Address. Accept only four canonical ASCII decimal octets (0–255), with no leading zeros or whitespace. Return one numeric value in network byte order, from 0 to 4294967295. Throw for malformed input, including IPv6. Do not emit diagnostic strings as results.
See an explained solution
function ConvertTo-IPv4Number {
param([Parameter(Mandatory)][AllowEmptyString()][string]$Address)
if ($Address -cnotmatch '\A(?:0|[1-9][0-9]{0,2})(?:\.(?:0|[1-9][0-9]{0,2})){3}\z') { throw 'Expected four canonical decimal octets.' }
[uint64]$value = 0
foreach ($part in $Address.Split('.')) {
$octet = [int]$part
if ($octet -gt 255) { throw 'Octet outside 0 to 255.' }
$value = $value * 256 + $octet
}
return $value
}
Whole-string validation rejects permissive parser shortcuts. The accumulation uses arithmetic on a wide unsigned value, so high-bit addresses do not become negative.