Created
October 9, 2018 14:28
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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