Created
February 9, 2021 15:48
-
-
Save serjmac/d6c3475ec44f6727425839fdbe251ed2 to your computer and use it in GitHub Desktop.
IP to integer and integer to IP
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
// ip example: "192.168.2.1" | |
module.exports = 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" | |
module.exports = 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