nodejs 获取本地局域网 ip 扫描本地端口

因为傻逼老板的垃圾需求,不得不成长

示例代码:
获取本地局域网  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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

某公司摸鱼前端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值