1

in my application users enter the ip address + sub net mask like this: 192.168.0.0/16 or 80.80.80.0/24 and i want to validate it like this:

  1. if the ip address is not a valid address then return false.(its easy and i can do it with IPAddress.TryParse method)
  2. if the ip address is not a public address then return false.(192.168.0.0/16=false)
  3. if the sub net mask is invalid.(its not between 0 and 32).

I'm new in c# and i really appreciated if you tell me the best way to validate the ip address. thank you.

Mohammad
  • 2,724
  • 6
  • 29
  • 55

2 Answers2

2

Please try to do some search because your question might has answered before.

For Q1, please refer to this stackoverflow article.

For Q2 and Q3, it can easily be checked after you split the input string (like @RPradeep's answer)

After all, I suggest you to find a better 3rd party "C# IP address library". I think your requirement is common usage and somebody might do the same before. It better than you do it again by yourself, right?

UPDATE

For Q2, there's still a stackoverflow article could help you.

UPDATE

According your comment, I recommend another way for you - how about list all IP address which you want to return false, and check a target IP address can be found in the list or not?

For IPv4, there's a codeproject article can build the IP address list for you - in easy way.

Community
  • 1
  • 1
J.C
  • 633
  • 1
  • 13
  • 27
  • thank you. but i already search and unfortunately cant found any thing. if you know a dll or anything might help i really appreciated let me know. – Mohammad Jul 28 '15 at 06:00
  • I could provide what I know to you, but I recommend you practice your google-fu, sincerely :) Please see my updated answer. – J.C Jul 28 '15 at 06:04
  • thank you. i already saw this post. unfortunately its not occurrence. for example the 169.254.0.0/16 is not a valid ip address range. – Mohammad Jul 28 '15 at 07:05
  • @Dan Okay, so you want to check all about those reserved IP address which list in https://en.wikipedia.org/wiki/IPv4#Special-use_addresses ? I find another way, please see my newest update. – J.C Jul 28 '15 at 07:16
  • Thank you so much. but i think i found something better: [link](http://ipnetwork.codeplex.com/). what do you think? – Mohammad Jul 28 '15 at 07:24
  • I have read the documentation, I'm not sure it will cover all your question, but it worth a try. – J.C Jul 28 '15 at 07:28
0

Check if the string contains a ":", //This is IPv6

If the string starts with fd, then return false

Else: You can parse the String with split on "." //This is for IPv4 1. If it starts with 10. , then return false 2. If it starts with 172.16 , and subnet is 12 , then return false 3. If it starts with 192.168 , and subnet is 16, then return false

Finally, split on / and see the 2nd part and parse the Integer. If it does not fall in range of 0 and 32, then return false

RPradeep
  • 6,564
  • 1
  • 13
  • 11