Skip to content

Instantly share code, notes, and snippets.

@jppommet
Last active Jun 17, 2021
Embed
What would you like to do?
javascript conversion from ip address to long integer and vice versa
function int2ip (ipInt) {
return ( (ipInt>>>24) +'.' + (ipInt>>16 & 255) +'.' + (ipInt>>8 & 255) +'.' + (ipInt & 255) );
}
function ip2int(ip) {
return ip.split('.').reduce(function(ipInt, octet) { return (ipInt<<8) + parseInt(octet, 10)}, 0) >>> 0;
}
@alimovz

This comment has been minimized.

Copy link

@alimovz alimovz commented Jan 21, 2021

Great stuff, but do you have any advice as to how to make it work for IPv6?

@vivek-doshi-genea

This comment has been minimized.

Copy link

@vivek-doshi-genea vivek-doshi-genea commented Apr 29, 2021

Hi,

I've used both of your function, which converted "original_int -1062731546" to "converted ip 192.168.0.230"
Then I tried to reverse but it gave me "converted int 3232235750" instead of "-1062731546",

Here is the link to demo: https://stackblitz.com/edit/js-1ccktx

@ashtakshara

This comment has been minimized.

Copy link

@ashtakshara ashtakshara commented May 10, 2021

Both work fine, thanks.

@cstephe

This comment has been minimized.

Copy link

@cstephe cstephe commented Jun 17, 2021

Hi,

I've used both of your function, which converted "original_int -1062731546" to "converted ip 192.168.0.230"
Then I tried to reverse but it gave me "converted int 3232235750" instead of "-1062731546",

Here is the link to demo: https://stackblitz.com/edit/js-1ccktx

These methods don't work right, -1062731546 is correct, I'm just digging into this now, so I am not an expert, but anything over 128.0.0.0 goes into the negative space for 32 bit and would set the negative bit. or something like that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment