Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use os.networkInterfaces() to detect network address #492

Merged
merged 1 commit into from
Dec 3, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions bin/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const path = require('path');
const fs = require('fs');
const {promisify} = require('util');
const {parse} = require('url');
const dns = require('dns');
const os = require('os');

// Packages
Expand All @@ -24,9 +23,10 @@ const compression = require('compression');
const pkg = require('../package');

const readFile = promisify(fs.readFile);
const lookup = promisify(dns.lookup);
const compressionHandler = promisify(compression());

const interfaces = os.networkInterfaces();

const warning = (message) => chalk`{yellow WARNING:} ${message}`;
const info = (message) => chalk`{magenta INFO:} ${message}`;
const error = (message) => chalk`{red ERROR:} ${message}`;
Expand Down Expand Up @@ -154,6 +154,17 @@ const registerShutdown = (fn) => {
process.on('exit', wrapper);
};

const getNetworkAddress = () => {
for (const name of Object.keys(interfaces)) {
for (const interface of interfaces[name]) {
const {address, family, internal} = interface;
if (family === 'IPv4' && !internal) {
return address;
}
}
}
};

const startEndpoint = (endpoint, config, args, previous) => {
const {isTTY} = process.stdout;
const clipboard = args['--no-clipboard'] !== true;
Expand Down Expand Up @@ -188,14 +199,10 @@ const startEndpoint = (endpoint, config, args, previous) => {
localAddress = details;
} else if (typeof details === 'object' && details.port) {
const address = details.address === '::' ? 'localhost' : details.address;
const ip = getNetworkAddress();

localAddress = `http://${address}:${details.port}`;
try {
const {address: ip} = await lookup(os.hostname());
networkAddress = `http://${ip}:${details.port}`;
} catch (err) {
console.error(error(`DNS lookup failed: ${err.message}`));
}
networkAddress = `http://${ip}:${details.port}`;
}

if (isTTY && process.env.NODE_ENV !== 'production') {
Expand Down