JavaScript IP functions | липня 6, 2009
Маленький JS прототип для швидкої роботи з IP адресами. Сподіваюся, ви зможете знайти йому гідне застосування. Традиційна ліцензія BeerBSD, що значить, що якщо ви мені якось поставите пиво за цей кусник коду, то я абсолютно не ображуся. А так можете вільно використовувати його на свій власний розсуд, проте без будь яких гарантій.
Якщо вам потрібні коментарі до коду… хм… мабуть тоді вам не потрібен цей клас
Подописував коментарі, виправив невеликі погрішності, на виході отримали цілих два об`єкти замість одного
/** * @projectDescription JavaScript swiss knife for IP v4 manipulations * * @author Yevhen Moroz (Vedeney) http://vedeney.org.ua yevhen[dot]moroz[at]gmail[dot]com * @version 0.2 */ /** * Ip * @class The purpose of this function is to be a constructor for the Ip * object. Ip objects are used as wrapper for IpTool object. * @requires IpTool * @constructor * @param {mixed} ip Ip address in Internet address to Internet number format. */ var Ip = function(ip){ switch (true) { case (typeof(ip) == 'number'): this.ip = IpTool.long2ip(ip); break; case (typeof(ip) == 'string' && ip.indexOf('.') >= 0): this.ip = ip; break; case (typeof(ip) == 'string' && parseInt(ip) == ip): this.ip = IpTool.long2ip(parseInt(ip)); break; default: this.ip = false; break; } this.blocks = null; } /** * Validates IP address * @see IpTool#isValid * @return bool */ Ip.prototype.isValid = function() { return IpTool.isValid(this.ip); } /** * Converts Internet addresses to Internet numbers * @see IpTool#ip2long * @return mixed Number if the ip address is correct of false */ Ip.prototype.ip2long = function() { return IpTool.ip2long(this.ip); } /** * Returns IP address in standart (dotted string) fromat * Might me usefull if you have Number as an incomming argument * (Sorry Weber, there is no long2ip function, use IpTool.long2ip instead) * @return {mixed} */ Ip.prototype.getIp = function() { return (IpTool.isValid(this.ip))?this.ip:false; } /** * Calculate is IP match IP mask * @return {bool} */ Ip.prototype.netMatch = function(cidr) { return IpTool.netMatch(this.ip, cird); } /** * Set of IP functions */ var IpTool = { /** * Ip v4 address validation * @param {string} ip * @return {bool} */ isValid:function(ip){ this._require(ip); if (!ip) { return false; } ipBlocks = this._getParts(ip); return (!ipBlocks || 255 < Math.max(ipBlocks[1], ipBlocks[2], ipBlocks[3], ipBlocks[4]))?false:true; }, /** * Converts Internet addresses to Internet numbers * @link http://publibn.boulder.ibm.com/doc_link/en_US/a_doc_lib/libs/commtrf2/inet_addr.htm * @param {string} ip * @return {mixed} Number if the IP is correct or false */ ip2long:function(ip){ this._require(ip); if(!this.isValid(ip)) return false; ipBlocks = this._getParts(ip); long = ipBlocks[4]; long+= ipBlocks[3] * 256; long+= ipBlocks[2] * 65536; long+= ipBlocks[1] * 16777216; return long; }, /** * Converts Internet numbers to Internet addresses * @param {number} long * @return {mixed} Address in Internet standard format (dotted string) representation or false */ long2ip:function(long){ this._require(long); if (!long || long < 0 || long > 4294967295) { return false; } var ip1 = Math.floor(long/16777216); var ip2 = Math.floor((long%16777216)/65536); var ip3 = Math.floor(((long%16777216)%65536)/256); var ip4 = Math.floor(((long%16777216)%65536)%256); return ip1 + '.' + ip2 + '.' + ip3 + '.' + ip4; }, /** * Calculate is IP matchs IP mask * @param {string} ip * @param {string} cidr * @retur {bool} */ netMatch:function(ip, cidr){ this._require(ip); this._require(cidr); if (!this.isValid(ip)) { this._error("Invalid ip adress(" + ip + ")"); } var net = cidr.split('/',2); if(this.isValid(net[1]) || 'undefined' == typeof(net[1]) || parseInt(net[1]) != net[1]) { this._error("Invalid cidr"); } var mask = parseInt(net[1]); return ((parseInt(this.ip2long(ip), 10).toString(2).substr(0, mask)) == (parseInt(this.ip2long(cidr), 10).toString(2).substr(0, mask))) ?true:false; }, /** * Split IP address * @private * @param {string} ip * @return {mixed} Array of IP blocks or false */ _getParts:function(ip){ this._require(ip); blocks = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/); if(blocks) { blocks[1] = parseInt(blocks[1]); blocks[2] = parseInt(blocks[2]); blocks[3] = parseInt(blocks[3]); blocks[4] = parseInt(blocks[4]); } return blocks; }, /** * Error raising * @throws * @param {string} err_txt Error text */ _error:function(err_txt) { throw "IpTool: " + err_txt; }, /** * Validates incomming arguments * @param {mixed} arg */ _require:function(arg){ if (typeof(arg) == 'undefined') { this._error('Argument missed'); } } }; /* Some test and examples */ var ips = new Array( '192.168.1.0', 2147417850, '2147417850', // Same nubmer as above /* All the arguments below are incorrect IP addresses, just for test */ '256.1.1.0', 4294967296, {}, new Array(), false, '' ); /* document.write shortcut */ var echo = function(str){ document.write(str + "<br>"); }; for (var i = 0; i < ips.length; i++) { echo("Type: (" + typeof(ips[i]) + ") Value: (" + ips[i].toString() + ")"); echo('Results:'); var ip = new Ip(ips[i]); echo('isValid -->' + ip.isValid()); echo('ip2long -->' + ip.ip2long()); echo('getIp -->' + ip.getIp()); echo("==============================="); }
липня 7, 2009 at 10:20
мені точно не потрібен цей клас.
..але щодо пива – я не проти