UNPKG

ip-subnet-calculator

Version:

Calculate optimal subnet masks for standard and non-standard IP ranges

2 lines (1 loc) 1.71 kB
"use strict";(()=>{var p=t=>{let r=0,e;for(e=0;e<t;e+=1)r+=1<<32-(e+1)>>>0;return r},k=t=>{let r=0,e;for(e=0;e<t;e+=1)r+=1<<e>>>0;return r},f=t=>{if(typeof t!="string")return!1;let r=t.match(/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/);if(r===null)return!1;for(let e=1;e<=4;e+=1){let n=parseInt(r[e],10);if(n>255||n<0)return!1}return!0},i=t=>typeof t=="number"&&t%1===0&&t>=0&&t<=4294967295,a=t=>{if(typeof t=="number"&&i(t))return t;if(typeof t!="string"||!f(t))throw new Error(`Not an IP address: ${t}`);let r=t.split(".");return((+r[0]*256+ +r[1])*256+ +r[2])*256+ +r[3]},c=t=>{if(typeof t=="string"&&f(t))return t;if(typeof t!="number"||!i(t))throw new Error(`Not a numeric IP address: ${t}`);let r=`${t%256}`,e=t;for(let n=3;n>0;n-=1)e=Math.floor(e/256),r=`${e%256}.${r}`;return r},u=(t,r)=>{let e=p(r),n=k(32-r),o=(t&e)>>>0,l=((t&e)>>>0)+n>>>0;return{ipLow:o,ipLowStr:c(o),ipHigh:l,ipHighStr:c(l),prefixMask:e,prefixMaskStr:c(e),prefixSize:r,invertedMask:n,invertedMaskStr:c(n),invertedMaskSize:32-r}},x=(t,r)=>{let e,n=null;for(e=32;e>=0;e-=1){let o=u(t,e);if(o.ipLow===t&&o.ipHigh<=r)n=o;else break}return n},d=(t,r)=>{let e,n,o,l=[];try{e=a(t),n=a(r)}catch{return null}if(n<e)return null;for(o=e;o<=n;){let s=x(o,n);if(s===null)return null;l.push(s),o=s.ipHigh+1}return l},w=(t,r)=>{let e;try{e=a(t)}catch{return null}return u(e,r)},h=(t,r)=>{let e,n,o=0,l=0,s;try{e=a(t),n=a(r)}catch{return null}for(s=0;s<32&&(l=o+(1<<32-(s+1))>>>0,(n&l)>>>0===l);s+=1)o=l;return u(e,s)};typeof window<"u"&&(window.IPSubnetCalculator={calculate:d,calculateSubnetMask:w,calculateCIDRPrefix:h,getOptimalRange:x,getMaskRange:u,toString:c,toDecimal:a,isDecimalIp:i,isIp:f,getMask:k,getPrefixMask:p});})();