Honestly, I think the code which I've written is trash and I don't think it's the best way to solve the problem. I need a few suggestions or improvements to solve this problem. I'm still new to coding. Appreciate it if you can give some tips on how to work with strings and various string functions.
CONDITIONS FOR THE STRING TO BE AN IP ADDRESS:-
An identification number for devices connected to the internet. An IPv4 addresses written in dotted quad notation consists of four 8-bit integers separated by periods.
In other words, it's a string of four numbers each between 0 and 255 inclusive, with a "." character in between each number. All numbers should be present without leading zeros.
Examples:
- 192.168.0.1 is a valid IPv4 address
- 255.255.255.255 is a valid IPv4 address
- 280.100.92.101 is not a valid IPv4 address because 280 is too large to be an 8-bit integer (the largest 8-bit integer is 255)
- 255.100.81.160.172 is not a valid IPv4 address because it contains 5 integers instead of 4
- 1..0.1 is not a valid IPv4 address because it's not properly formatted
- 17.233.00.131 and 17.233.01.131 are not valid IPv4 addresses because they contain leading zeros
Here's my code (I know it's trash and doesn't make any sense):-
bool isIPv4Address(char * inputString) {
int count = 0, period = 0;
int k = 0, i = 0;
int digit = 0;
while(inputString[i] != '\0')
{
count = 0;
digit = 0;
i = k;
if(inputString[i] == '0' || inputString[i] == '.')
{
if(inputString[i+1] >47 && inputString[i+1] < 58)
{
return false;
}
}
while(inputString[i] != '.' && inputString[i] != '\0')
{
if(inputString[i] < 48 || inputString[i] > 57)
{
return false;
}
count += (int)inputString[i];
i++;
digit++;
}
if(digit == 3)
{
if(inputString[i - 3] > '2')
{
return false;
}
}
if(inputString[i] == '.')
{
period++;
}
k = i+1;
if(count < 48 || count > 156)
{
return false;
}
if(inputString[i] == '\0')
{
break;
}
}
if(period == 3)
{
return true;
}else
{
return false;
}
}