Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert IPv4 to Integer using CoffeScript?

In CoffeeScript how would I go about converting an IP (standard IPv4 127.0.0.1) into an integer?

EDIT: Lots of great answers here, thanks everyone!

like image 540
Marco Avatar asked Dec 05 '11 23:12

Marco


2 Answers

EDIT: Coffeescript

ipStringToInteger = (x) ->
  res = 0
  (res = res * 256 + Number(y) for y in x.split("."))
  res

which compiles down to

var ipStringToInteger;
ipStringToInteger = function(x) {
  var res, y, _i, _len, _ref;
  res = 0;
  _ref = x.split(".");
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    y = _ref[_i];
    res = res * 256 + Number(y);
  }
  return res;
};

A short pure Javascript implementation is

var ipV4StringToInteger = function(string) {
  var parts = string.split(".");

  var sum = 0;

  for(var i = 0; i < 4; i++) {
    var partVal = Number(parts[i]);
    sum = (sum << 8) + partVal;
  }

  return sum;
};

A good pure Javascript implementation is

var ipV4StringToInteger = function(string) {
  var parts = string.split(".");
  if(parts.length != 4)
    throw new Error("IPv4 string does not have 4 parts.");

  var sum = 0;

  for(var i = 0; i < 4; i++) {

    var part = parts[i];
    if(!part.match("^\\d+$"))
      throw new Error("Non-digit, non-period character in IPv4 string.");

    var partVal = Number(part);
    if(partVal > 255)
      throw new Error("IPv4 string contains invalid value.");

    sum = ((sum << 8) + partVal) >>> 0;
  }

  return sum;
};
like image 108
ellisbben Avatar answered Sep 22 '22 01:09

ellisbben


To convert an ip to integer you need the formula

(first octet * 256³) + (second octet * 256²) + (third octet * 256) + (fourth octet)

Let ip = '127.0.0.1', that could be written as:

integer = 0
for octet, i in ip.split('.')
    integer += octet * Math.pow 256, 3-i

And it can be simplified using the reduce method:

integer = ip.split('.').reduce ((t, n) -> t*256 + parseInt n), 0
like image 36
Ricardo Tomasi Avatar answered Sep 19 '22 01:09

Ricardo Tomasi