equivalent of INET_ATON() in mongodb

匿名 (未验证) 提交于 2019-12-03 08:51:18

问题:

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]); } 

From here: IP-addresses stored as int results in overflow?



回答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('.'); } 

http://rolfrost.de/ipjs.html



回答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("."); }  


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!