Convert a signed or unsigned int to an IP address - Node.js Network

Node.js examples for Network:IP Address

Description

Convert a signed or unsigned int to an IP address

Demo Code

/**/*  www  .  j a v  a  2 s  . co  m*/
 * ExtendJs Number extensions v1.0.0 (https://github.com/mkenney/ExtendJs)
 *
 * Copyright 2014 Michael Kenney
 *
 * Licensed under MIT (https://github.com/mkenney/ExtendJs/blob/master/LICENSE)
 */

+function(undefined) {
  'use strict';

  /**
   * Convert a signed or unsigned int to an IP address
   *
   * Matches the PHP long2ip() function
   *
   * @param  {Number} ip_long Long IP address value
   * @return {String}         IPv4 address
   */
  Number.prototype.toIp = function() {
    var quads = [0,0,0,0];
    var divisor = 16777216.0;
    var ip_long = this+0.0;
    if (ip_long < 0) {
      ip_long += 4294967296; // 2^32
    }

    for (var a = 0; a < 4; a++) {
      var quad = Number(ip_long / divisor).format(0);
      ip_long = ip_long - (divisor * quad);
      quads[a] = quad;
      divisor = (divisor / 256.0);
    }
    return quads.join('.');
  };

Related Tutorials