I'm doing an application that uses IP address. I have to validate them to start from at least 1.0.0.1 but with the codes below it accepts 0.0.0.0:
\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
I also tried changing it to:
\b(25[0-5]|2[0-4][0-9]|[01]?[1-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
This code does not accept 0.0.0.0 but does not accept 100.0.0.0 to 109.0.0.0 either.
Can someone help?
A valid IP address must be in the form of A.B.C.D, where A,B,C and D are numbers from 0-255. The numbers cannot be 0 prefixed unless they are 0. Note:You only need to implement the given function. Do not read input, instead use the arguments to the function.
You could use inet_pton() to try parsing the string first as an IPv4 ( AF_INET ) then IPv6 ( AF_INET6 ). The return code will let you know if the function succeeded, and the string thus contains an address of the attempted type.
The FILTER_VALIDATE_IP filter validates an IP address. Possible flags: FILTER_FLAG_IPV4 - The value must be a valid IPv4 address. FILTER_FLAG_IPV6 - The value must be a valid IPv6 address.
Class C network addresses range from 192.0. 0.0 to 223.255. 255.0. There are over 2 million possible Class C networks.
Use
IPAddress addr = IPAddress.TryParse(str);
Then, if that worked get the numbers using
addr.GetAddressBytes();
and then check the byte values for the correct conditions using normal if-cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With