LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [SOLVED] Detect if input is a valid ip & subnet (https://www.linuxquestions.org/questions/programming-9/%5Bsolved%5D-detect-if-input-is-a-valid-ip-and-subnet-4175610005/)

pan64 07-18-2017 06:59 AM

If it was that difficult: I would simply try to execute ping.
Code:

If ping does not receive any reply packets at all it will exit with code 1.
If a packet count and deadline are both specified,
and fewer than count packets are received by the time the deadline has arrived, it will also exit with code 1.
On other error it exits with code 2.
Otherwise it exits with code 0.
This makes it possible to use the exit code to see if a host is alive or not.


pedropt 07-18-2017 08:44 AM

The finality is not to check if ip is active but if ip is correct .
And without even mention that you are unable to ping a subnet like 192.168.1.1/24 ;)

However , i already fixed everything .

Here it is the code in bash with check if ip is between 0.0.0.0/0-255.255.255.255/32

Quote:

#!/bin/bash
function ckf () {
st="0"
tr "." "\n" <tmp >tmp1
splt=$(cat tmp1 | tr "." "\n")

for nmb in $splt
do

if [[ "$nmb" -ge "0" ]] && [[ "$nmb" -le 255 ]]
then
st=$((st+1))
if [ $st == "4" ]
then
ok=`cat tmp`
echo "Valid Ip : $ok"
fi
else
if [ $st -lt "4" ]
then
ok=`cat tmp`
echo "Invalid IP : $ok"
exit 1
fi
fi

done

rm -f tmp >/dev/null 2>&1
rm -f tmp1 > /dev/null 2>&1

}
echo -ne "Enter IP or IP range : ";tput sgr0
read ips
echo $ips > tmp
ip="$ips"
if [[ $ip =~ "/" ]]
then
chk="/"
chk1=`grep -o $chk <<< "$ip" | wc -l`
if [ $chk1 != 1 ]
then
echo "Invalid IP"
exit 1
else
sub=`cat tmp | cut -d "/" -f 2`
if [[ ! $sub =~ ^[^A-Za-z]+$ ]]; then
echo "Invalid IP"
exit 1
else
if [ $sub -lt "0" ]
then
echo "Invalid IP"
elif [ $sub -gt "32" ]
then
echo "Invalid IP"
exit 1
else
ipo=`cat tmp | cut -f1 -d "/"`
ckf
fi
fi
fi
else
echo $ips > tmp
ckf
fi
Basically almost every code can be done in bash programming , the problem is the amount of options that must be written .
It is almost the same thing as you using a plugin or active x controller in C or VB , you can do what the activex is doing by hand , the difference is the amount of code that must be written to contemplate that activex options .

business_kid 07-19-2017 03:15 AM

Another difference is speed; sysvinit is very slow running successive bash scripts by comparison with init-ng or systemd, or multithreaded binaries. What I would call intermediate languages (perl, python, etc.) are in the middle. Assembler can be difficult to code, especially as you increase in system complexity, but it's hellish fast.


All times are GMT -5. The time now is 01:18 AM.