Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate ip address in C#

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?

like image 730
james Avatar asked Jul 14 '11 08:07

james


People also ask

How do I validate my IP address?

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.

How do you check IP address is IPv4 or IPv6 in C?

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.

Which script correctly validates an IP address?

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.

What is a valid Class C IP 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.


1 Answers

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.

like image 67
Anders Forsgren Avatar answered Sep 17 '22 02:09

Anders Forsgren