UNPKG

1.32 kBPlain TextView Raw
1import * as os from "os";
2import {Logger} from "@simplism/core";
3
4export class CliHelper {
5 public static getCurrentIP(hostOrHosts: string | string[] | undefined): string {
6 const selectors = hostOrHosts
7 ? typeof hostOrHosts === "string"
8 ? [hostOrHosts] as string[]
9 : hostOrHosts as string[]
10 : [undefined];
11
12 for (const selector of selectors) {
13 if (selector && !selector.includes(".")) {
14 return selector;
15 }
16
17 const ipRegExpString = selector
18 ? selector.replace(/\./g, "\\.").replace(/\*/g, "[0-9]*")
19 : ".*";
20
21 const ifaces = os.networkInterfaces();
22 const result = Object.keys(ifaces)
23 .map(key => ifaces[key].filter(item => item.family === "IPv4" && !item.internal))
24 .filter(item => item.length > 0).mapMany(item => item.map(item1 => item1.address))
25 .filter(addr => new RegExp(ipRegExpString).test(addr));
26 if (result.length < 1) {
27 continue;
28 }
29 if (result.length > 1) {
30 new Logger("@simplism/cli", "CliHelper: ").warn(`IP ${result.join(", ")}${result[0]}이 선택되었습니다.`);
31 }
32 return result[0];
33 }
34
35 throw new Error(`"${selectors.join(`", "`)}"와 매칭되는 아이피 주소를 찾을 수 없습니다.`);
36 }
37}