JavaScript 打印 IP 地址列表

JavaScript print a list of IP address

我想允许用户以

格式输入一系列 ip 地址
10.5.15.[22-25],10.5.16.[35-37],10.5.17.20

和return一个数组(用于稍后的连接检查)

10.5.15.22
10.5.15.23
10.5.15.24
10.5.15.25
10.5.16.35
10.5.16.36
10.5.16.37
10.5.17.20

我尝试了 npm 包 iprange,但它会生成给定子网中的所有 ip。我是 JavaScript 的新手,正在寻找一个简单的 library/solution,谢谢!

form.html:

<body>
<form action="/check" method="post">
<fieldset>
IP address(es): <input type="text" name="ipaddr"><br>
<input type="submit" value="submit" />
</fieldset>
</form>
</body>

server.js

var express = require('express')
var http = require('http');
var bodyParser = require('body-parser');

var app = express()
var iprange = require('iprange');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())

app.get('/', function (req, res, next) {
  res.sendFile(__dirname + '/form.html');
});

app.post('/check', function (req, res, next) {
  checkcon(req.body, res);
});

app.listen(8080);

function checkcon(parms, res) {
  var ipaddr = parms.ipaddr;
  var range = iprange(ipaddr);
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end("Host IP address(es):" + range);
}

希望此代码段将 useful.Have 添加评论以描述这些步骤

function getIp() {
  var ip = document.getElementById('ipInput').value;
  // split the input to get the values before [
  var ipMask = document.getElementById('ipInput').value.split('[')[0];
  //Use regex to get the text inside [] & split it
  var getRange = ip.match(/\[([^)]+)\]/)[1].split('-');
  // iterate over that range 
  for (var i = getRange[0]; i <= getRange[1]; i++) {
    console.log(ipMask + i)
  }
}
<input type="text" id="ipInput" value="10.5.15.[22-25]">
<button id="ipButton" onclick="getIp()">GetIp</button>

使用正则表达式:

const data = '10.5.15.[22-25],10.5.16.[35-37],10.5.17.20';
// Placeholder for the final result
const result = [];

// Use the split function to get all your Ips in an array
const ips = data.split(',');

// Use the built in forEach function to iterate through the array
ips.forEach(ip => {
  // This regular expression will match the potential extremities of the range
  const regexp = /[0-9]+\.[0-9]+\.[0-9]+\.\[(.*)\-(.*)\]/;
  const match = regexp.exec(ip);
  
  // If it's a range
  if (match && match.length && match[1] && match[2]) {
      // Iterate through the extremities and add the IP to the result array
      for (let i = parseInt(match[1]); i <= parseInt(match[2]); i ++) {
        result.push(ip.match(/[0-9]+\.[0-9]+\.[0-9]+\./i)[0] + i);
      }
  } else { // If it is a single IP
    // Add to the results
    result.push(ip);
  }
});

console.log(result);