DEV Community

James Moberg
James Moberg

Posted on

ColdFusion isIPInRange() UDF to support IPv4, IPv6, CIDR & Regex

I received reports of 502 server errors this morning after our web application framework accidentally blacklisted our CDN/WAF provider. I wanted to ensure that this wouldn't happen again by whitelisting their IPs, but they have many IPs and their data was only available in IPv4 & IPv6 CIDR notation.

ColdFusion doesn't have any built-in IP-related tools other than determining the IP of the current host... so I'm off to search for a potential existing solution.

I checked CFDocs and discovered that there was an isIPInRange function (without any examples), but it was a Lucee-only function. The Lucee function accepts either a comma-separated list or an array of IP definitions, but doesn't support CIDR or Regex.

I checked CFLib and discovered that there was a isIPInRange UDF with the same name from 2005 that used a list of regex values, but it didn't support CIDR or dash-delimited range (well, unless you wanted to write the regex for that).

I had been using a method that Anjo Gakhar blogged about in 2008 that demonstrates the use of the undocumented coldfusion.util.IPAddressUtils class to identify whether a string is a valid IPv4 or IPv6 IP address or not.

I then found a 2018 blog post by Ben Nadel documenting his implementation of using Commons IP Math to check if an IPv4 or IPv6 IP exists in a CIDR range, but it is dependent on separate java library (MIT) called Commons IP Math. The code example also only supported a single CIDR range.

Since none of the existing solutions fully covered my needs, I decided to write my own ColdFusion UDF and combine the best features from all of them.

  • Performs IPv4 & IPv6 validation
  • Supports IPv4 & IPv6 CIDR range notation
  • Supports list or array of ranges
  • Supports regex range rules
  • Supports dash-delimited IP address range
  • Supports single IP (versus a range)
  • Requires Commons IP Math JAR File

Since all my web applications are behind a CDN/WAF and could be negatively impacted if the CDN was blacklisted, I figured it was best for me to add the JAR to the global path instead of using Javaloader. I also didn't write this as a stand-alone CFC like Ben does. Most of my projects use a global UDF library and this was the simplest approach to integrate since I wouldn't have to manually update every project.

Source Code

Here's a link to the gist. Due to the JAR requirement, this unfortunately can't be demoed using TryCF.

[ ]

Discussion (0)