Skip to content

Instantly share code, notes, and snippets.

@cmcdevitt
Created October 9, 2018 14:28
Show Gist options
  • Select an option

  • Save cmcdevitt/d1a0f757bd6321c0ea209e8ec399c5b2 to your computer and use it in GitHub Desktop.

Select an option

Save cmcdevitt/d1a0f757bd6321c0ea209e8ec399c5b2 to your computer and use it in GitHub Desktop.
Check to see if an IPv4 Address is in CIDR Range in a ServiceNow Script Include
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'
};
//https://community.servicenow.com/community?id=community_question&sys_id=54b1cb69db98dbc01dcaf3231f96198a
/* Usage Example
var ip = '192.168.1.4';
var cidr = '192.168.1.0/24';
var cu = new CidrUtil();
gs.log(cu.ipIsInCidr(ip, cidr)); //Return true
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment