Mirror: Best-effort discovery of the machine's local network using just Node.js dgram sockets
at main 815 B view raw
1import { createSocket } from 'dgram'; 2 3const PROBE_PORT = 53; 4const PROBE_IP = '1.1.1.1'; 5const NO_ROUTE_IP = '0.0.0.0'; 6 7class DefaultRouteError extends TypeError { 8 code = 'ECONNABORT'; 9} 10 11export const probeDefaultRoute = (): Promise<string> => { 12 return new Promise((resolve, reject) => { 13 const socket = createSocket({ type: 'udp4', reuseAddr: true }); 14 socket.on('error', error => { 15 reject(error); 16 socket.close(); 17 socket.unref(); 18 }); 19 socket.connect(PROBE_PORT, PROBE_IP, () => { 20 const address = socket.address(); 21 if (address && 'address' in address && address.address !== NO_ROUTE_IP) { 22 resolve(address.address); 23 } else { 24 reject(new DefaultRouteError('No route to host')); 25 } 26 socket.close(); 27 socket.unref(); 28 }); 29 }); 30};