-
Notifications
You must be signed in to change notification settings - Fork 95
/
myip
executable file
·66 lines (60 loc) · 1.59 KB
/
myip
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env node
//
// Show my local and external IP addresses.
//
// - Show both local and external IP:
//
// `myip`
//
// - Show local IP:
//
// `myip l`
//
// - Show external (public) IP:
//
// `myip g`
//
// ---
// Author: Nick Plekhanov, https://nikkhan.com/
// License: MIT
// https://github.com/nicksp/dotfiles
const { execSync } = require('node:child_process')
const https = require('node:https')
const os = require('node:os')
function getLocalIP() {
return Object.values(os.networkInterfaces())
.flat()
.filter((details) => details.family === 'IPv4' && !details.internal)
.map((details) => details.address)[0]
}
function getExternalIP() {
return new Promise((resolve, reject) => {
https
.get('https://icanhazip.com/', (res) => {
if (res.statusCode !== 200) {
reject(`${res.statusCode} error from upstream`)
return
}
res.on('data', (chunk) => {
resolve(chunk.toString().trim())
})
})
.on('error', reject)
})
}
async function main() {
const args = process.argv.slice(2)
const wantsLocal = args.includes('local') || args.includes('l')
const wantsGlobal = args.includes('global') || args.includes('g')
const wantsBoth =
args.includes('gl') || args.includes('lg') || (wantsLocal && wantsGlobal)
if (wantsBoth || (!wantsLocal && !wantsGlobal)) {
console.log('local:', getLocalIP())
console.log('external:', await getExternalIP())
} else if (wantsLocal) {
console.log(getLocalIP())
} else if (wantsGlobal) {
console.log(await getExternalIP())
}
}
main().catch(console.error)