aton and ntoa functions in node.js

Due to the lack of support for a IP address data type in MongoDB those who want to be able to search IP ranges have to come up with other ways to support this. One of the generally accepted ways to do this is to store the IP address as an Integer. This requires aton() and ntoa() functions. A google search for most languages will turn up those functions pretty easily, but I noticed for node.js there wasnt much. I did happen to find this thread: http://stackoverflow.com/questions/15987750/equivalent-of-inet-aton-in-mongodb which outlined a way to do this in browser JS, however, it doesn't translate 100% to node.

With that in mind I figured I'd adapt the functions for node.js. Here's what I came up with:

aton()

function aton(ip){
  var a = ip.split('.');
  var buf = new Buffer(4);
  for(var i = 0; i < 4; i++){
    buf.writeUInt8(a[i], i);
  }
  return buf.readUInt32BE(0);
}

ntoa()

function ntoa(num){
  var buf = new Buffer(4);
  buf.writeUInt32BE(num, 0);

  var a = [];
  for(var i = 0; i < 4; i++){
    a[i] = buf.readUInt8(i);
  }

  return a.join('.');
}

Credit to Rolf Rost for the original, making my life easier in creating a node version.