Skip to content

Instantly share code, notes, and snippets.

@jesseky
Created July 15, 2021 02:38
Show Gist options
  • Save jesseky/9b8fbd3b56c18f74a91a4fc57f018938 to your computer and use it in GitHub Desktop.
Save jesseky/9b8fbd3b56c18f74a91a4fc57f018938 to your computer and use it in GitHub Desktop.
js convert ip to int, int to ip
const ip2int = ip => ip.split('.').reverse().map((v, i) => +v << (8 * i)).reduce((s, a) => s | a);
const int2ip = it => it.toString(2).padStart(32, 0).match(/.{8}/g).map(v => parseInt(v, 2)).join('.');
// test
console.log(ip2int(`127.0.0.1`)); // 2130706433
console.log(int2ip(2130706433)); // 127.0.0.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment