I study the C programming language, I have a task to determine the validity of an IP address. My program has obvious problems and doesn't do what I intended. I ask those who understand, please point out the errors in my program. It is important not to do the work, but to understand how it works. Recommend good tools for catching errors in code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
bool isIpAddress(char *arg1);
bool isSegment(int arg1);
int main()
{
char ipaddress[17];
scanf("%s", ipaddress);
if(isIpAddress(ipaddress) == true)
printf("%s is a valid IP address\n", ipaddress);
else
printf("%s is not a valid IP address\n", ipaddress);
return 0;
}
bool isIpAddress(char *arg1){
short counterSegment = 0;
short counterDot = 0;
char *segment;
char *dot = ".";
bool temp;
segment =(char *) malloc(17 * sizeof(char));
for (int i = 0; i < strlen(arg1); i++)
{
if(arg1[i] == '.')
counterDot++;
}
while (arg1)
{
segment = strtok(arg1, dot);
temp = isSegment(atoi(segment));
if(segment == NULL)
return 0;
else if(temp == true){
counterSegment++;
arg1 += strlen(segment);
if(arg1 == NULL)
return 0;
arg1 += strlen(dot);
}
}
free(segment);
if(counterSegment == 4 && counterDot == 3)
return true;
else
return false;
}
bool isSegment(int arg1){
if(arg1 >= 0 && arg1 <= 255)
return true;
else
return false;
}