Based on the answer from @ktaka I don't recommend using
ip route get to validate IP addresses unless your script depends heavily on the network connection. The reason is because, if your system does not have a good internet connection or is completely disconnected from the internet, then when you use
ip route get, your script will always return error code (other than 0) even the IP is correctly defined.
I looked up the manual link given by @Rolf Rander and I was confused why my
ipcalc binary on Debian 11 does not have the
-c option, and also my previous
ipcalc binary does not support
ipv6. So, I searched on Google the author username taken from the manual page with this keyword
dcantrell ipcalc and I got the official link here:
So the above is the official
ipcalc that supports both IPv4 and IPv6 IP addresses. To install this, they recommend using the modern build with meson (but they also provided old make build if you don't want to use meson)
So, this is how I setup
Remove existing ipcalc (the existing version is not good)
apt-get -y remove ipcalc
rm -rf "/usr/bin/ipcalc"
Now install ipcalc from the official repo here:
apt -y install meson
git clone https://gitlab.com/ipcalc/ipcalc.git
meson setup build --buildtype=release
ninja -C build
cp build/ipcalc /usr/bin
apt -y remove meson
Now you can use this
ipcalc to check both IPv4 and IPv6:
if ipcalc -s -c $IP; then
echo "valid IPv4 or IPv6"
echo "Invalid IPv4 or Ipv6"
-s is to ignore error message, the
-c is for checking without output
If you want to check specific IPv4 use
-4 or use
-6 to check IPv6. Example:
# IP is a valid IPv6
# But we want to check only IPv4
if ipcalc -s -4 -c $IP; then
echo "valid IPv4"
echo "Invalid IPv4"
I have been using
ipv6calc long time ago and they can do both IPv4 and IPv6 checking, but I do like more on
ipcalc because most of the output are simple and it has json output for other purposes.
Based on the latest comment from @ktaka, my main point was that when using
ip route get without internet connection like below:
$ ip route get 192.168.0.255 ; echo $?
RTNETLINK answers: Network is unreachable
it is not going to return a valid IP if your system is behind firewall or you have a bad connection. The IP is valid, and it should return the success code of 0, instead of telling unnecessary things like unreachable network.
ssh 2130706433to confirm that many 32-bit ints are valid IP addresses. Two 16-bit ints separated by a dot are also valid, etc.
IPv6 is more complex (as it supports compression of zeroes). Just IPv6? Try a
ping 127.1and see the result from IP v4
pingI'm wondering if I could use that? It seems to return status
2if given an invalid address (like
'foo'), but status 1 if a ping was sent (valid address) but no response was received. Is this reliable enough to use? i.e- status 0 and status 1 = well formed IP?