nthmail / lib / alloc.js
all-in-one smtp+imap with minimal setup
git clone http://git.nthia.dev/nthmail

const tcpWrap = process.binding('tcp_wrap')
const TCP = tcpWrap.TCP
const errno = require('util')._errnoException

module.exports = function (addr, port) {
  if (typeof addr === 'number' || /^\d+$/.test(addr)) {
    ;[port,addr] = [addr,port]
  }
  if (port === undefined) port = 0
  if (addr === undefined) addr = '0.0.0.0'
  let h = new TCP(tcpWrap.constants && tcpWrap.constants.SERVER)
  if (/:/.test(addr)) {
    h.bind6(addr, port)
  } else {
    h.bind(addr, port)
  }
  let sock = {}
  let s = h.getsockname && h.getsockname(sock)
  if (s || (port && port !== sock.port)) {
    throw errno('EADDRINUSE', 'bind')
  }
  return h.fd
}