How to convert IPv4 to Integer using CoffeScript?
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;
};
I'll take the bit-shifting approach:
ip_to_int = (value) ->
result = 0
for part, i in value.split "."
result |= part << (3-i) * 8
result
To use it is simple:
alert ip_to_int "127.0.0.1"
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