Skip to content

Instantly share code, notes, and snippets.

@nethoncho
Last active October 10, 2024 19:47
Show Gist options
  • Save nethoncho/53b3b7e4dfe68a4de34f to your computer and use it in GitHub Desktop.
Save nethoncho/53b3b7e4dfe68a4de34f to your computer and use it in GitHub Desktop.
JavaScript inet_aton
// 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('.');
}
@andreas83
Copy link

would be cool to have ipv6 support as well

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