# Javascript中IP地址和无符号整数之间的相互转换

IP地址转换成无符号整数，javascript中没有无符号数，不过位运算>>>能把整型转换成无符号数值

//IP转成无符号数值
function IP2Num(ip)
{
var num = 0;
ip = ip.split(".");
num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]);
num = num >>> 0;
return num;
}

//无符号转成IP地址
function Num2IP(num)
{
var str;
var tt = new Array();
tt[0] = (num >>> 24) >>> 0;
tt[1] = ((num << 8) >>> 24) >>> 0;
tt[2] = (num << 16) >>> 24;
tt[3] = (num << 24) >>> 24;
str = String(tt[0]) + "." + String(tt[1]) + "." + String(tt[2]) + "." + String(tt[3]);
return str;
}

//判断是不是合法的子网掩码
{
var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}\$/;
return false;
var i = 0;
var a = -1;
var str = tt.toString(2);
for (i = 0; i < str.length; i++)
{
if (str.charAt(i) == "0")
a = i;
if (str.charAt(i) == "1" && a > -1)
return false;
}
return true;
}

//使用示例
function CheckIP( ip, mask, gateway )
{
var a,b,mk, m, n;
a = IP2Num(ip);
b = IP2Num(gateway);
m = (a & mk)>>>0;
n = (b & mk)>>>0;
if( m != n )
return false;
if( a == m || a == m+~mk )
return false;
if( b == m || b == m+~mk )
return false;
return true;
}

function Test()
{
var ip="192.168.0.3";
var gateway = "192.168.0.1";
if( CheckIP( ip, mask, gateway) == false )
}