Last active
October 10, 2024 19:47
-
-
Save nethoncho/53b3b7e4dfe68a4de34f to your computer and use it in GitHub Desktop.
JavaScript 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
// http://stackoverflow.com/a/21559595 | |
// ip example: 192.168.2.1 | |
function inet_aton(ip){ | |
// split into octets | |
var a = ip.split('.'); | |
var buffer = new ArrayBuffer(4); | |
var dv = new DataView(buffer); | |
for(var i = 0; i < 4; i++){ | |
dv.setUint8(i, a[i]); | |
} | |
return(dv.getUint32(0)); | |
} | |
// num example: 3232236033 | |
function inet_ntoa(num){ | |
var nbuffer = new ArrayBuffer(4); | |
var ndv = new DataView(nbuffer); | |
ndv.setUint32(0, num); | |
var a = new Array(); | |
for(var i = 0; i < 4; i++){ | |
a[i] = ndv.getUint8(i); | |
} | |
return a.join('.'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
would be cool to have ipv6 support as well