Validate canonical IPv4 addresses
Validate dotted-decimal IPv4 before converting an address into a number.
A dotted string is not yet an address
An IPv4 address has four octets, each between 0 and 255. A pattern that merely finds digits and dots can accept extra components or values outside that range. This lesson also requires canonical decimal spelling: zero is allowed, but an octet such as 01 is rejected. That keeps the input unambiguous across parsers.
Validate the whole field before arithmetic. Shell arithmetic can interpret a leading zero as octal, and unchecked text does not belong in an arithmetic expression. Here a fixed awk function validates each octet, then builds the integer by repeatedly multiplying the accumulated value by 256 and adding the next octet.
Separate validity from address purpose
The number zero is a valid conversion result. Use a separate negative sentinel for invalid input rather than treating zero as false. Likewise, syntactic validity does not mean an address is public, assigned, reachable or suitable for a particular interface.
The resulting range is zero through 4294967295. Format it with %.0f to avoid platform-dependent signed integer formatting at the upper boundary. Later lessons use these integers for containment and prefix comparisons. IPv6 needs a different parser and is outside these IPv4 exercises; do not apply this four-octet function to IPv6 text.
awk 'BEGIN {printf "%.0f\n",192*16777216+0*65536+2*256+10}'
Put it into practice.
Read addresses.txt, one candidate per line including empty lines. Print address<TAB>number<TAB>state in input order. Accept exactly four canonical decimal octets, each 0–255: no whitespace, sign, leading zeros (except 0), extra dots or trailing text. Valid rows contain the unsigned decimal integer and valid; invalid rows contain - and invalid. Zero and 255.255.255.255 are syntactically valid. Do not change the source file.
See an explained solution
export LC_ALL=C
printf 'address\tnumber\tstate\n'
awk 'function ipv4(s,a,n,i,v) {
n=split(s,a,"."); if(n!=4)return -1
v=0
for(i=1;i<=4;i++) {
if(a[i]!~/^(0|[1-9][0-9]*)$/ || length(a[i])>3 || a[i]>255)return -1
v=v*256+a[i]
}
return v
}
function dotted(v,a,b,c,d) {
a=int(v/16777216);v-=a*16777216
b=int(v/65536);v-=b*65536
c=int(v/256);d=v-c*256
return sprintf("%d.%d.%d.%d",a,b,c,d)
}
function cidr(s,a,n,p,v) {
n=split(s,a,"/")
if(n!=2 || a[2]!~/^(0|[1-9][0-9]*)$/ || length(a[2])>2 || a[2]>32)return 0
v=ipv4(a[1]);if(v<0)return 0
prefix=a[2]+0;block=2^(32-prefix);first=int(v/block)*block;last=first+block-1
return 1
}
{v=ipv4($0);if(v<0)printf "%s\t-\tinvalid\n",$0;else printf "%s\t%.0f\tvalid\n",$0,v}
' addresses.txt
Validation happens before arithmetic, so unusual spellings and command-shaped text remain data. The negative sentinel separates invalid candidates from the valid lower boundary, and decimal formatting preserves the full IPv4 range.