---
title: "Javascript 实现 php的 ip2long long2ip"
author: "Nonkr"
date: "2012-02-29T13:09:23Z"
tags: []
categories: ["Web前端"]
slug: "javascript-php-ip2long-long2ip"
draft: false
lastmod: "2012-02-29T13:09:23Z"
id: 1431711
url: "https://nonkr.iteye.com/blog/1431711"
---

```
$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;
}
```