我希望允许用户以
格式输入一系列IP地址10.5.15.[22-25],10.5.16.[35-37],10.5.17.20
并返回一个数组(稍后进行连接检查)
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,但它产生了给定子网中的所有ips。我是JavaScript的新手,正在寻找一个简单的库/解决方案,谢谢!
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);
}
答案 0 :(得分:1)
希望这段代码很有用。添加了评论来描述步骤
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>
答案 1 :(得分:1)
使用正则表达式:
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);
&#13;