Javascript 实现 php的 ip2long long2ip

 

$ip = "192.0.34.166";
$long = ip2long($ip);

echo $ip . "\n";                          // 192.0.34.166
echo $long . "\n";                      // -1073732954
printf("%u\n", ip2long($ip));      // 3221234342

 

 

上面的PHP中ip2long的使用方法,我们会发现,有些ip转化成整数后,是负的,这是因为得到的结果是有符号整型,最大值是2147483647.要把它转化为无符号的。

 

 

$gateway = "192.168.1.1";
$netmask = "255.255.255.0";

//网络地址
$ip1 = ip2long($gateway) & ip2long($netmask);

//广播地址
$ip2 = ip2long($gateway) | (~ip2long($netmask));

 

 

在javascript当中实现ip2long和long2ip,需要对网络上流传的代码做一些改写,将ip2long的无符号转成有符号,将long2ip的有符号转成无符号,代码如下:

 

function ip2long ( ip_address ) {
    var output = false;
    if ( ip_address.match ( /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ ) ) {
      var parts = ip_address.split ( '.' );
      var output = 0;
      output = ( parts [ 0 ] * Math.pow ( 256, 3 ) ) +
               ( parts [ 1 ] * Math.pow ( 256, 2 ) ) +
               ( parts [ 2 ] * Math.pow ( 256, 1 ) ) +
               ( parts [ 3 ] * Math.pow ( 256, 0 ) );
    }
    
    return output<<0;
}

function long2ip ( proper_address ) {
	proper_address = proper_address>>>0;
    var output = false;
   
    if ( !isNaN ( proper_address ) && ( proper_address >= 0 || proper_address <= 4294967295 ) ) {
      output = Math.floor (proper_address / Math.pow ( 256, 3 ) ) + '.' +
               Math.floor ( ( proper_address % Math.pow ( 256, 3 ) ) / Math.pow ( 256, 2 ) ) + '.' +
               Math.floor ( ( ( proper_address % Math.pow ( 256, 3 ) ) % Math.pow ( 256, 2 ) ) /
Math.pow ( 256, 1 ) ) + '.' +
               Math.floor ( ( ( ( proper_address % Math.pow ( 256, 3 ) ) % Math.pow ( 256, 2 ) ) %
Math.pow ( 256, 1 ) ) / Math.pow ( 256, 0 ) );
    }
   
    return output;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值