Skip to content

实现 IPv4 展开 工具

分类:developer | 标签:IPv4、CIDR、展开 CIDR/范围展开为 IP 列表

2.1 功能说明

CIDR/范围展开为 IP 列表

2.1.1 使用指南

功能说明

将 CIDR(如 192.168.1.0/30)或起止范围展开为全部 IP 列表(上限 65536)。

使用场景

网络扫描清单、批量配置。

2.2 代码实现

2.2.1 组件结构

本工具是一个基于 Vue 3 <script setup> 语法的单文件组件(SFC),统一包裹在 ToolPageShell 组件内,由它提供页面标题、工具 ID、分类与「使用指南」插槽等通用外壳;核心业务逻辑(响应式状态、计算属性、事件处理函数)全部写在 <script setup> 中,输入/输出通过 el-inputel-button 等 Element Plus 组件与用户交互,所有数据均在浏览器本地处理,不会上传服务器。

2.2.2 核心逻辑概览

<script setup> 中定义的主要函数/方法:

  • toInt()
  • toIp()
  • run()
  • copy()
  • clear()

2.2.3 关键实现代码

以下是该工具的完整 <script setup> 实现(核心代码)。模板(<template>)与样式(<style>)已省略。

vue
import { ref } from 'vue'
import ToolPageShell from '@/components/ToolPageShell.vue'

const input = ref('')
const out = ref('')
const count = ref(null)
const error = ref('')

function toInt(ip) {
  const p = ip.trim().split('.').map(Number)
  if (p.length !== 4 || p.some(x => !Number.isInteger(x) || x < 0 || x > 255)) return null
  return (p[0] << 24) + (p[1] << 16) + (p[2] << 8) + p[3]
}
function toIp(n) { return [(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join('.') }
function run() {
  error.value = ''; out.value = ''; count.value = null
  const s = input.value.trim()
  if (!s) { error.value = '请输入范围'; return }
  let start, end
  if (s.includes('/')) {
    const [ip, pre] = s.split('/')
    const base = toInt(ip); const p = Number(pre)
    if (base === null || !Number.isInteger(p) || p < 0 || p > 32) { error.value = 'CIDR 格式无效'; return }
    start = base & (p === 0 ? 0 : 0xffffffff << (32 - p))
    end = start + (1 << (32 - p)) - 1
  } else if (s.includes('-')) {
    const [a, b] = s.split('-')
    start = toInt(a); end = toInt(b)
  } else { error.value = '格式:CIDR 或 起-止'; return }
  if (start === null || end === null) { error.value = 'IP 格式无效'; return }
  if (end < start) { error.value = '结束地址小于起始地址'; return }
  if (end - start + 1 > 65536) { error.value = '地址数量超过上限 65536'; return }
  const arr = []
  for (let n = start; n <= end; n++) arr.push(toIp(n))
  out.value = arr.join('\n'); count.value = arr.length
}
function copy() { if (out.value) navigator.clipboard?.writeText(out.value) }
function clear() { input.value = out.value = error.value = ''; count.value = null }

2.3 效果截图

IPv4 展开 效果截图

工具访问地址:https://www.i91tools.com/tools/ipv4-expand