Skip to content

Issue 4630/replace default gateway #5255

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

Merged
63 changes: 18 additions & 45 deletions lib/Server.js
Original file line number Diff line number Diff line change
Expand Up @@ -378,57 +378,30 @@ class Server {
return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(URL);
}

/**
* @param {string} gateway
* @returns {string | undefined}
*/
static findIp(gateway) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to keep this function, because developer still can use it, otherwise it is a breaking change

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, I'll change my changes.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

const gatewayIp = ipaddr.parse(gateway);

// Look for the matching interface in all local interfaces.
for (const addresses of Object.values(os.networkInterfaces())) {
for (const { cidr } of /** @type {NetworkInterfaceInfo[]} */ (
addresses
)) {
const net = ipaddr.parseCIDR(/** @type {string} */ (cidr));

if (
net[0] &&
net[0].kind() === gatewayIp.kind() &&
gatewayIp.match(net)
) {
return net[0].toString();
}
}
}
}

/**
* @param {"v4" | "v6"} family
* @returns {Promise<string | undefined>}
*/
static async internalIP(family) {
try {
const { gateway } = await require("default-gateway")[family]();

return Server.findIp(gateway);
} catch {
// ignore
}
}

/**
* @param {"v4" | "v6"} family
* @returns {string | undefined}
*/
static internalIPSync(family) {
try {
const { gateway } = require("default-gateway")[family].sync();
let host;
Object.values(os.networkInterfaces())
.flatMap((networks) => networks ?? [])
.filter(
(network) =>
network &&
network.address &&
network.family === `IP${family}` &&
// I'm not sure whether I need to only filter to internal IP address
network.internal === true,
)
.forEach((network) => {
host = network.address;
if (host.includes(":")) {
host = `[${host}]`;
}
});

return Server.findIp(gateway);
} catch {
// ignore
}
return host;
}

/**
Expand Down
Loading