0

I want to validate(just check if the IP address is in correct format with and without network mask) the IP address which has network mask say example : 192.168.0.254/32. This should give result as valid IP address.

I can verify it with this Regex expression Regex(@"\b\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\b/\d{1,3}\b|\b\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\b");

However can the IP address be verified by IPAddress.TryParse or any other existing method ?

Edit to confirm for not similar question : Here i want to check if the IP address is in correct format with and without network mask in one check

usr021986
  • 3,421
  • 14
  • 53
  • 64
  • That RE isn't really verifying the IP address is valid. You should be doing something more like `(([0-2]\d\d|\d\d?)\.){4}/(3[0-2]|[0-2]\d|\d)`. – NetMage Sep 24 '18 at 20:56
  • You're probably better off using regex for this anyway. [This answer explains the pitfalls of using `IPAddress.TryParse`](https://stackoverflow.com/a/11412991/9070959) – emsimpson92 Sep 24 '18 at 20:56
  • @NetMage: I want to verify the IP address format is valid or not and it is working for me. can you please give one example for which the regex i mentioned will not work – usr021986 Sep 24 '18 at 22:01
  • `\d{1,3}` matches `999` –  Sep 24 '18 at 22:03
  • @sln: okay got it. I just wanted to checking if the format of IP is valid only.like it will be valid for 123.121.124.221. I will check other option. – usr021986 Sep 24 '18 at 22:23
  • @NetMage: I found one article saying "regex is dangerous for validating IP addresses because of the different forms an IP address can take." https://www.perlmonks.org/index.pl?node_id=221512 – usr021986 Sep 24 '18 at 22:38
  • That article is about using regex to restrict the acceptable IP address range. Verifying that a string constitutes any valid IP address is a much easier problem, and a regex is a reasonable solution. – NetMage Sep 25 '18 at 17:31

1 Answers1

1

Here is a pattern you can use to validate a string represents a valid four octet IP address, with an optional net mask, using regex:

(?:(?:[0-2]\d\d|\d\d?)\.){3}(?:[0-2]\d\d|\d\d?)(?:/(?:3[0-2]|[0-2]\d|\d))?
NetMage
  • 26,163
  • 3
  • 34
  • 55