james
james

Reputation: 107

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?

Upvotes: 5

Views: 6618

Answers (3)

vml19
vml19

Reputation: 3864

Try using this,

ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";

Upvotes: 0

Barry Kaye
Barry Kaye

Reputation: 7761

Save yourself the pain! Convert to a string, split on the dot character and check whether each of the 4 segments is in the range 0 or 1 to 255.

Otherwise if you use RegexBuddy (which is a fantastic app for RegEx) it has a bunch of IP address examples in the Library inc for 0.0.0.0 to 255.255.255.255:

\b(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b

Upvotes: 1

Anders Forsgren
Anders Forsgren

Reputation: 11101

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.

Upvotes: 10

Related Questions