Last active
August 29, 2015 14:27
-
-
Save vilicvane/5f18685a8f9220e09cf1 to your computer and use it in GitHub Desktop.
Node.js. Get server IPs (v4) information (WAN/LAN IPs).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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