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):

cidr_chart-2

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:

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.

Let me know if this helps you!

Update: Found a little bug and corrected it.

2 thoughts on “Validate IP Addresses and Slash Notation

  1. “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.”

    FYI, since you’re the copyright owner, nothing prevents you from double-licensing your code. That is, release it to the public under any license you want (e.g. GPL), and keep a version for yourself for your closed-source application (for example Qt and MySQL do business that way). The only issue could be if somebody improves your code (under the GPL), then you would not be able to integrate it back into your closed-source app.

    In any case, for such short piece of code, what you did, that is releasing it in the public domain (if I get it right, because there is an “All rights reserved” in the code, and a contradicting statement in your text), is probably the easiest thing to do.

    Best,

    • Hi, and thanks for your comment.

      That was indeed my opinion as well in the end. Given the size of the piece of code and because I am the author but my University holds the copyright, the easiest thing to do was just to release it to the public domain and leave it like that. By the way, “All rights reserved” does not contradict “your may freely use it”… 🙂

      Cheers!

Leave a Reply

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

*