日期:2014-05-16  浏览次数:20277 次

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;
}
?