What is the equivalent of INET_ATON() in mongodb? I am using nodejs with mongodb so if a equivalent in nodejs is avaliable than it is good enough.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Here's someone else's solution for converting an IP address from a dotted-decimal string to a 32-bit number:
function dot2num(dot) { var d = dot.split('.'); return ((((((+d[0])*256)+(+d[1]))*256)+(+d[2]))*256)+(+d[3]); }
回答2:
// 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('.'); }
回答3:
function inet_aton(ip){ var a = new Array(); a = ip.split('.'); return((a[0] << 24) >>> 0) + ((a[1] << 16) >>> 0) + ((a[2] << 8) >>> 0) + (a[3] >>> 0); } function inet_ntoa(n){ var a = ((n >> 24) & 0xFF) >>> 0; var b = ((n >> 16) & 0xFF) >>> 0; var c = ((n >> 8) & 0xFF) >>> 0; var d = (n & 0xFF) >>> 0; return(a + "." + b + "." + c + "." + d); }
as of my site see below/above, compatible with older browsers.
回答4:
Here's a version of the ntoa function in Javascript using typed arrays.
function ntoa(ipInt) { var buffer = new ArrayBuffer(4); var uint8View = new Uint8Array(buffer); var uint32View = new Uint32Array(buffer); uint32View[0] = ipInt; var ipSegments = []; for (var i = 0; i < uint8View.length; i ++) { ipSegments.push(uint8View[i]); } return ipSegments.join("."); }