Skip to content

Instantly share code, notes, and snippets.

@morbeo
Created February 20, 2024 08:44
Show Gist options
  • Save morbeo/952369bf6fe648188200e6acc8e4ed07 to your computer and use it in GitHub Desktop.
Save morbeo/952369bf6fe648188200e6acc8e4ed07 to your computer and use it in GitHub Desktop.
bash IP validation
192.168.1.1
10.0.0.1
172.16.254.1
224.0.0.1
127.0.0.1
8.8.8.8
255.255.255.255
1.2.3.4
192.0.2.123
203.0.113.0
1.hi.2.3
256.1.1.1
192.168.1.256
-1.0.0.0
192.168.1.1.1
192.168.1
10.0.0.999
172.16.254.01
224.0.0.256
127.0.0.0.1
300.2.3.4
.1.2.3.4
...1.2.3...4.
1.2...3..4
for ip in $(<ips_test_data); do
valid_ip.sh "${ip}"
case $? in
0) echo "✅ ${ip} valid IP";;
1) echo "❌ ${ip} invalid IP (expected 3 delimiters - [0-255].[0-255].[0-255].[0-255])";;
2) echo "❌ ${ip} invalid IP (expected 4 octets - [0-255].[0-255].[0-255].[0-255])";;
3) echo "❌ ${ip} invalid IP (octet $((octet+1)): ${ip_array[$octet]} is out of range [0-255])";;
4) echo "❌ ${ip} invalid IP (octet $((octet+1)): ${ip_array[$octet]} leading zeros not allowed)";;
5) echo "❌ ${ip} invalid IP (octet $((octet+1)): '${ip_array[$octet]}' non-numeric characters not allowed)";;
esac
done
#!/usr/bin/env bash
ip=$1 ip_array=(${1//\./ })
if [[ "${ip}" =~ (^\.+|\.\.+|\.+$) ]]; then exit 1 # incorrect delimiters
elif [[ "${#ip_array[@]}" -ne 4 ]]; then exit 2 # incorrect octets
fi
for octet in {0..3}; do
if [[ ${ip_array[$octet]} -lt 0 ||
${ip_array[$octet]} -gt 255 ]]; then exit 3 # out of bounds
elif [[ ${ip_array[$octet]} =~ ^0[0-9] ]]; then exit 4 # leading zero
elif [[ ${ip_array[$octet]} =~ [^0-9] ]]; then exit 5 # non numerical characters
fi
done
@morbeo
Copy link
Author

morbeo commented Feb 20, 2024

I wanted to create an IP validation script that does not rely solely on regex.
It is reduced to 5 assert statements.

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