Wednesday, April 8, 2020

How to convert CIDR to IP Addresses Range using JavaScript



Many times, when you work on IP Exclusions in Google Analytics, you are required to create IP Addresses range in RegEx format. We have seen how to write a proper RegEx to exclude or include IP Address range in Google Analytics in our previous post. In this post, let us see how to convert a CIDR notation to a range of starting and ending IP addresses using plain JavaScript. CIDR (Classless Inter-Domain Routing, sometimes called supernetting) is an easy way to put a range of IP addresses in a single expression. Unfortunately you cannot enter a CIDR IP in Google Analytics. You have to create a range of starting and ending IP addresses and then come up with a Regular Expression to set them up in the filter. When you have a list of CIDR IPs and it gets frustrating to convert all of them manually going to some website which has a converter and then write the RegEx.

In this post, I have come up with a JavaScript function which you can use quickly to convert a CIDR IP to a starting and ending IP address which you can further use to form a RegEx.



I don't think there is a need to explain the code as it can get technical in understanding all the details related to CIDR which if you would like to understand can read here. All we need to understand is if you supply the CIDR IP Range as an argument to the function, it will give you the starting and the ending IP as an array.

If you are looking for a converter where you can supply a list of CIDR ranges and get the starting and ending IP in a CSV file, I have created one for you and you can use the below form.



No comments :

Post a Comment