Created
February 20, 2024 08:44
-
-
Save morbeo/952369bf6fe648188200e6acc8e4ed07 to your computer and use it in GitHub Desktop.
bash IP validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wanted to create an IP validation script that does not rely solely on regex.
It is reduced to 5 assert statements.