1'use strict'; 2 3const { 4 FunctionPrototypeBind, 5 Symbol, 6} = primordials; 7 8const { codes } = require('internal/errors'); 9const { UDP } = internalBinding('udp_wrap'); 10const { guessHandleType } = internalBinding('util'); 11const { isInt32 } = require('internal/validators'); 12const { UV_EINVAL } = internalBinding('uv'); 13const { ERR_INVALID_ARG_TYPE, ERR_SOCKET_BAD_TYPE } = codes; 14const kStateSymbol = Symbol('state symbol'); 15let dns; // Lazy load for startup performance. 16 17 18function lookup4(lookup, address, callback) { 19 return lookup(address || '127.0.0.1', 4, callback); 20} 21 22 23function lookup6(lookup, address, callback) { 24 return lookup(address || '::1', 6, callback); 25} 26 27function newHandle(type, lookup) { 28 if (lookup === undefined) { 29 if (dns === undefined) { 30 dns = require('dns'); 31 } 32 33 lookup = dns.lookup; 34 } else if (typeof lookup !== 'function') { 35 throw new ERR_INVALID_ARG_TYPE('lookup', 'Function', lookup); 36 } 37 38 if (type === 'udp4') { 39 const handle = new UDP(); 40 41 handle.lookup = FunctionPrototypeBind(lookup4, handle, lookup); 42 return handle; 43 } 44 45 if (type === 'udp6') { 46 const handle = new UDP(); 47 48 handle.lookup = FunctionPrototypeBind(lookup6, handle, lookup); 49 handle.bind = handle.bind6; 50 handle.connect = handle.connect6; 51 handle.send = handle.send6; 52 return handle; 53 } 54 55 throw new ERR_SOCKET_BAD_TYPE(); 56} 57 58 59function _createSocketHandle(address, port, addressType, fd, flags) { 60 const handle = newHandle(addressType); 61 let err; 62 63 if (isInt32(fd) && fd > 0) { 64 const type = guessHandleType(fd); 65 if (type !== 'UDP') { 66 err = UV_EINVAL; 67 } else { 68 err = handle.open(fd); 69 } 70 } else if (port || address) { 71 err = handle.bind(address, port || 0, flags); 72 } 73 74 if (err) { 75 handle.close(); 76 return err; 77 } 78 79 return handle; 80} 81 82 83module.exports = { 84 kStateSymbol, 85 _createSocketHandle, 86 newHandle 87}; 88