Skip to content

Instantly share code, notes, and snippets.

@sveesible
Created May 3, 2016 21:59
Show Gist options
  • Save sveesible/d22ae619ddbc489591094b608aef7be2 to your computer and use it in GitHub Desktop.
Save sveesible/d22ae619ddbc489591094b608aef7be2 to your computer and use it in GitHub Desktop.
Validate IP Address from user input in Bash
#!/bin/bash
read -p "What is your IP address?" my_ip
read valid <<< $( awk -v ip="$my_ip" '
BEGIN { n=split(ip, i,"."); e = 0;
if (6 < length(ip) && length(ip) < 16 && n == 4 && i[4] > 0 && i[1] > 0){
for(z in i){if (i[z] !~ /[0-9]{1,3}/ || i[z] > 256){e=1;break;}}
} else { e=1; } print(e);}')
if [ $valid == 0 ]; then
echo "Success: IP Valid"
else
echo "Fail: IP Invalid"
fi
@riedoi
Copy link

riedoi commented Nov 16, 2018

thanks for the function, I use it for school project :) but there is a small mistake:
on line 7 it should be >= 256 , otherwise the user can enter 256 as IP

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment