因为傻逼老板的垃圾需求,不得不成长
示例代码:
获取本地局域网 ip 地址:
需要注意的是:如果存在虚拟机网络,则返回的是虚拟机网络的 ipv4 地址
import os from 'os';
export const getLocalIp = () => {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const net of interfaces[name]) {
if (net.family === 'IPv4' && !net.internal) {
return net.address;
}
}
}
return 'Can not get local IP';
};
扫描本地端口:
因为我需要查找本地几个 ip 的 3000 端口是否开放 可根据实际需求自行修改部分代码:
import os from 'os';
import net from "net";
const { Socket } = net;
const timeout = 100;
export const getLocalIp = () => {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const net of interfaces[name]) {
if (net.family === 'IPv4' && !net.internal) {
return net.address;
}
}
}
return 'Can not get local IP';
};
const scanHostPort = (host, port, cb) => {
return new Promise((resolve, reject) => {
const socket = new Socket();
socket.setTimeout(timeout);
socket.on("connect", function () {
console.debug(`链接成功:${host}`);
socket.end();
cb && cb(null, host);
resolve(host);
});
socket.on("timeout", function () {
// console.error(`链接超时:${host}`);
socket.destroy();
cb && cb(new Error("timeout"), host);
resolve(false);
});
socket.on("error", function (err) {
// console.warn(`链接失败:${host}`);
cb && cb(err, host);
resolve(false);
});
socket.on("close", function (err) {});
socket.connect(port, host);
});
}
export const scanIPs = async () => {
const current_ip = getLocalIp();
let current_ip_parts = current_ip.split('.');
current_ip_parts.pop();
current_ip_parts = current_ip_parts.join('.');
const deferCache = [];
for (let index = 0; index <= 255; index++) {
deferCache.push(scanHostPort(`${current_ip_parts}.${index}`,3000));
}
const result = (await Promise.all(deferCache)).filter((it) => it);
return result;
}