Last active
March 6, 2023 20:46
-
-
Save ArtskydJ/1259790f7deefd53c1bea4c7c8ff5833 to your computer and use it in GitHub Desktop.
Convert IP addresses to integers in javascript, similar to MySQL INET_NTOA and INET_ATON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// An earlier version did not work when the first part of the IP address was greater than 127. (e.g. '192.168.0.1') | |
// JS uses signed integers for bitshifting operations, which broke | |
// The issue is fixed now, but I really don't like my code. | |
// Maybe use this instead: https://gist.github.com/nethoncho/53b3b7e4dfe68a4de34f | |
const inet_ntoa = n => [3,2,1,0].map(i => ((n & (255 << (8 * i))) >>> 0) / Math.pow(256, i)).join('.') | |
const inet_aton = ip => ip.split('.', 4).map(Number).map((byte, i) => byte << (8 * (3 - i))).reduce((a, b) => a + b) >>> 0 | |
inet_aton('10.0.5.9') // => 167773449 | |
inet_ntoa(167773449) // => '10.0.5.9' | |
inet_aton('192.168.0.1') // => 3232235521 | |
inet_ntoa(3232235521) // '192.168.0.1' | |
inet_ntoa(inet_aton('0.255.0.128')) // => '0.255.0.128' | |
inet_ntoa(inet_aton('3.255.47.128')) // => '3.255.47.128' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment