php和js实现根据子网掩码和ip计算子网功能示例

时间:2021-08-24 13:04:59

本文实例讲述了php和js实现根据子网掩码和ip计算子网功能。分享给大家供大家参考,具体如下:

php

?
1
2
3
4
5
6
7
8
9
10
11
<?php
$ip = '192.168.6.1';
$mask = '255.255.2.0';
$sub_net = array();//子网
$ip_explode = explode('.', $ip);
$mask_explode = explode('.', $mask);
foreach ($ip_explode as $key => $ip_num) {
  $sub_net[] = (int)$ip_num & (int)$mask_explode[$key];
}
$sub_net = implode('.', $sub_net);
echo $sub_net;

运行结果:

192.168.2.0

js

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script>
var ip = '192.168.6.1';
var mask = '255.255.255.0';
var sub_net = [];//子网
var ip_explode = ip.split('.');
var mask_explode = mask.split('.');
  console.log('ip_explode='+ip_explode);
  console.log('mask_explode='+mask_explode); for (var i = 0, num = ip_explode.length; i < num; i++) {
  c = parseInt(ip_explode[i]) & parseInt(mask_explode[i]);
  console.log('c='+c);
  sub_net.push(c);
}
sub_net = sub_net.join('.');
console.log(sub_net);
</script>

运行结果:

php和js实现根据子网掩码和ip计算子网功能示例

希望本文所述对大家PHP程序设计有所帮助。

原文链接:https://www.cnblogs.com/jdhu/p/4246228.html