Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Function to determine if IP is in CIDR network?

jason_lau
Tera Contributor

Is there an existing script class I can use to determine if an IP address is in a given CIDR range?

Basically I want to make a call like: isInCIDR(ip_addr, cidr) and it returns true or false. I'd like to do this without first converting CIDR to range and then using SncIPRangeV4 for example.

Or as a corollary, is there a function I can call where given an IP address, it will return the IP Network (cmdb_ci_ip_network) that IP belongs to, regardless if I have that IP address mapped in CMDB.

1 ACCEPTED SOLUTION

Chuck Tomasi
Tera Patron

Hi Jason,



Thanks for the inquiry. As far as I know, there's nothing OOB. It sounded like a fun thing to build on a weekend so... here's a script include you can use.



var CidrUtil = Class.create();


CidrUtil.prototype = {


  initialize: function() {


  },



  ipIsInCidr : function(ip, cidr) {


            var cidrIp = cidr.split('/')[0];


            var cidrSm = cidr.split('/')[1];



            return (this.IPnumber(ip) & this.IPmask(cidrSm)) == this.IPnumber(cidrIp);


  },



  IPnumber : function (IPaddress) {


            var ip = IPaddress.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);


            if(ip) {


                      return (+ip[1]<<24) + (+ip[2]<<16) + (+ip[3]<<8) + (+ip[4]);


            }


            // else ... ?


            return null;


  },



  IPmask : function(maskSize) {


            return -1<<(32-maskSize);


  },


  type: 'CidrUtil'


};



Here's a small example how it can be used:



var ip = '192.168.1.4';


var cidr = '192.168.1.0/24';



var cu = new CidrUtil();


gs.log(cu.ipIsInCidr(ip, cidr));


View solution in original post

16 REPLIES 16

jonathanriehle
Giga Contributor

Just to add to the above script:

The IP-validation in the 'IPnumber'-function checks for digit.digit.digit.digit .

That check would work for numbers outside the legal ip range though.

E.G.: 10.1.1.1 is a valid ip and gets through. 10.300.300.300 is a non-valid-ip and passes the check as well.

Therefor to tighten the regex replace the

var ip = IPaddress.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);

with

var ip = IPaddress.match(/^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/);

 

source: https://stackoverflow.com/a/12142961

laurelin
Mega Contributor

Is there anything like this for ipV6?

Our business rules seem to be using an SncIPNetworkV4 library to calculate low/high addresses in a subnet if the address is v4.  But nothing like this is happening for ipv6 addresses.  I can find no documentation whatsoever on the various SncIP* scripts.

Thanks in advance, lauri