Converts an IPv4 address ({[0-255].[0-255].[0-255].[0-255]}) to a number. - Node.js Network

Node.js examples for Network:IP Address

Description

Converts an IPv4 address ({[0-255].[0-255].[0-255].[0-255]}) to a number.

Demo Code


// Copyright 2012 Rackspace Hosting, Inc.
///*from  w w w  .j  a  v a  2 s  .  c om*/
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * Formatters that can be used by tracers.  RESTkin expects the trace and
 * annotations to be a particular JSON format, and Zipkin/Scribe expects
 * base64-encoded thrift objects.
 */

  /**
   * Converts an IPv4 address ({[0-255].[0-255].[0-255].[0-255]}) to a number.
   * If the address is ill-formatted, raises an error
   *
   * formula is (first octet * 256^3) + (second octet * 256^2) +
   *    (third octet * 256) + (fourth octet)
   *
   * @param {String} ipv4 String containing the IPv4 address
   */
  ipv4ToNumber = function(ipv4) {
    var octets = ipv4.split(".");
    var sum = 0, i;

    if(octets.length !== 4) {
      throw new Error("IPv4 string does not have 4 parts.");
    }

    for (i=0; i<4; i++) {
      var octet = parseInt(octets[i], 10);
      if (isNaN(octet) || octet < 0 || octet > 255) {
        throw new Error("IPv4 string contains a value that is not a number " +
                        "between 0 and 255 inclusive");
      }

      sum = (sum << 8) + octet;
    }

    return sum;
  };

Related Tutorials