Skip to content

Instantly share code, notes, and snippets.

@vilicvane
Last active August 29, 2015 14:27
Show Gist options
  • Save vilicvane/5f18685a8f9220e09cf1 to your computer and use it in GitHub Desktop.
Save vilicvane/5f18685a8f9220e09cf1 to your computer and use it in GitHub Desktop.
Node.js. Get server IPs (v4) information (WAN/LAN IPs).
/*
Server IP Information Utils
by VILIC VANE <https://github.com/vilic>
MIT License
*/
import * as OS from 'os';
export interface IPInfo {
lanIP: string;
wanIP: string;
}
export function getIPInfo(): IPInfo {
let interfacesMap = OS.networkInterfaces();
let lanIP: string;
let wanIP: string;
outer:
for (let deviceName of Object.keys(interfacesMap)) {
let interfaces = interfacesMap[deviceName];
for (let interface of interfaces) {
if (
interface.internal ||
interface.family != 'IPv4' ||
interface.mac == '00:00:00:00:00:00' ||
/^169\.254\./.test(interface.address)
) {
continue;
}
let address = interface.address;
let numbers = address
.split('.')
.map(n => Number(n));
if (
numbers[0] == 10 ||
(numbers[0] == 172 && (numbers[1] >> 4) == 1) ||
(numbers[0] == 192 && numbers[1] == 168)
) {
if (!lanIP) {
lanIP = address;
if (wanIP) {
break outer;
}
}
} else {
if (!wanIP) {
wanIP = address;
if (lanIP) {
break outer;
}
}
}
}
}
if (!wanIP) {
// for test purpose.
wanIP = lanIP;
}
return { lanIP, wanIP };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment