Validate IP Addresses and Slash Notation

I’m currently working on a project that requires the user to provide a target IPv4 address within a LAN for a network analysis. The address may indicate a single host (i.e. 10.0.2.25) or it may use “slash notation” to designate a group of IP addresses according to the Classless Inter-Domain Routing (CIDR) Chart (i.e. 10.0.2.0/24):

Google found several regular expressions that were supposed to filter out valid IP addresses but none of them included the slash notation, and many of them didn’t even work correctly.

I finally decided to write my own from scratch and put it all in a function to determine if an IP address (or network) is valid. I believe it works as expected:

code
Let me know if this helps you!You may freely use this code if you wish, but I’m not officially releasing it under any open source license because I need my other code that integrates this to remain closed source.

Update: Found a little bug and corrected it.

One Reply to “Validate IP Addresses and Slash Notation”

Leave a Reply

Your email address will not be published. Required fields are marked *

*