Please only answer D,E,c2,D2,E2 2) (13 points) The following Bourne shell script
ID: 3698475 • Letter: P
Question
Please only answer D,E,c2,D2,E2 2) (13 points) The following Bourne shell script and C program can accomplish the same task: read an IP address from user's input and check if the input IP address is valid or not. Shell script C program #2 /bin/bash echo-n "Please enter the ip:" echo $iplgrepB # include int main) int ipl-0,ip2-0,ip3-0,ip4-0; int n-0 A2. then echo "Please enter IP address following the IP address pattern f (n!-4) I exit printf("Please enter IP address fi following the IP address pattern" 5 replace the dots in ip with spaces ?P".echo $1p 1 sed valid-1 int valid-0 for nun in sip if (ip1
Explanation / Answer
Shell Script
#!/bin/bash
echo -n "Please enter the ip: "
#A
read ip 3
# check if IP follows the correct pattern
# B
echo $ip | grep '^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$'
# C
if [ $ip -ne ]
then
echo "Please enter IP address following the
IP address pattern"
exit
fi
#replace the dots in ip with spaces
# D
ip=`echo $ip | sed "s/./ /g"`
valid=1
n=1
for num in $ip
do
# E
if [ $num > 255 -o $num < 0 ]
then
echo "INVALID: Please enter a number
between 0-255 in field $n (index starts
from 1 from left)"
valid=0
exit
fi
n=`expr $n + 1`
done
if [ $valid -eq 1 ];then
echo "The ip you entered is valid"
fi
===============================================================
// C code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ip1 = 0, ip2 = 0, ip3 = 0, ip4 = 0;
int n = 0;
// A2 = "%d.%d.%d.%d"
// B2 = &ip1,&ip2,&ip3,&ip4
n = scanf("%d.%d.%d.%d", &ip1,&ip2,&ip3,&ip4);
if(n != 4)
{
printf("Please enter IP address following the IP address pattern ");
// C2
return 0;
}
int valid = 0;
if(ip1 < 0 || ip1 > 255) valid = 1;
else if(ip2 < 0 || ip2 > 255) valid = 2;
else if(ip3 < 0 || ip3 > 255) valid = 3;
// D2
else if(ip4 < 0 || ip4 > 255) valid = 4;
// E2
if (valid != 0 )
{
printf("INVALID: Please enter a number between 0-255 in field %d ",valid);
}
else
{
printf("the ip you entered is correct ");
}
}