ipcopy
Version:
Copy local/public IP-address into clipboard
69 lines (59 loc) • 1.87 kB
JavaScript
const exec = require('await-exec')
const chalk = require('chalk');
const os = require('os')
const getIP = {
/** get the public IP */
ipServerList: "ifconfig.cc|cip.cc|ipinfo.io|ip.sb|ifconfig.io|ifconfig.me|ident.me",
/** 0.0.0.0 - 255.255.255.255 */
ipRegx: /((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/,
/**
* @param {String} string
* @returns {Boolean}
*/
isVaild: function (string) {
return typeof string === 'string' && this.ipRegx.test(string);
},
errLog: (text) => {
console.log(chalk.bold.red(`\n=== ${text} ===\n`))
},
/**
* get your local-network IP without 127.0.0.1
* @returns {[String]}
*/
local: function () {
var interfaces = os.networkInterfaces()
let ipArr = [];
for (var dev in interfaces) {
let iface = interfaces[dev]
for (let i = 0; i < iface.length; i++) {
let { family, address, internal } = iface[i]
if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
ipArr.push(address)
}
}
}
return ipArr
},
/**
* get your public IP
* @param {String} ipServer Return your public IP-Server list, spilt with | , like "cip.cc|ip.sb"
* @returns {Promise<String>}
*/
public: function (ipServer) {
ipServer = ipServer || this.ipServerList;
const gIP = async (url) => {
const { stdout } = await exec(`curl ${url}`)
if (typeof stdout === "string" && this.isVaild(stdout)) return stdout
}
const racer = ipServer.split("|").map((url) => gIP(url));
return new Promise((resolve) => {
Promise.race(racer).then(res => {
const curIP = res.match(new RegExp(this.ipRegx, "g"))
return resolve(curIP[0])
}).catch(err => {
console.log(chalk.red("\n=== Network Error ===\n"))
})
})
}
}
module.exports = getIP