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

IP到数值的转换问题
function funIPToInt(strIP)
{
  var value = 0;
  var num = strIP.split(".");
  for(var i=0;i<4;i++)
  value += parseInt(num[i]) * Math.pow(256,3-i);
  return value;
}
//上面上我写的IP地址到数值的转换函数,工作正常

//下面调用此函数时遇到了些问题
//例如:子网IP=192.168.1.0,MASK=255.255.255.255要把它转换为IP范围应该是:192.168.1.0 到 192.168.1.255
//即 IP & MASK 到 IP & MASK + ~MASK ,程序实现时出现了负数,影响了判定!
var ip="192.168.1.0";
var mask="255.255.255.0";
var ipnum = funIPToInt(ip);
var masknum = funIPToInt(mask);
var startip = ipnum & masknum;
var endip = startip + ~masknum;
alert(startip); //-1062731520 变成了负值!!!!
alert(endip); //-1062731520 变成了负值!!!!

我期望的输出是:
alert(funIPToInt("192.168.1.0")); //3232235776
alert(funIPToInt("192.168.1.255")); //3232236031
//上面这两个数值才是我想要的结果,如果修改程序获得?????? 最好不要修该我的IP范围的数学算法,这是标准的网络判定方法







------解决方案--------------------
If IPvalidate("192.168.1.0", "192.168.1.250") = False Then
lblError.Text = "您不在IP地址限制范围!"
lblError.Visible = True
Exit Sub
End If

Function IPvalidate(ByVal strStartIP As String, ByVal strEndIP As String) As Boolean ''IP地址范围
Try
Dim strIP1 As String = Request.UserHostAddress.ToString
Dim strIPNow1() As String = Split(strIP1, ".")
Dim i As Long
For i = 1 To 3
If Len(strIPNow1(i)) = 1 Then
strIPNow1(i) = "00" & strIPNow1(i)
ElseIf Len(strIPNow1(i)) = 2 Then
strIPNow1(i) = "0" & strIPNow1(i)
End If
Next
Dim strIPOne1 As String = strIPNow1(0) & strIPNow1(1) & strIPNow1(2) & strIPNow1(3)

Dim strIPNow2() As String = Split(strStartIP, ".")
For i = 1 To 3
If Len(strIPNow2(i)) = 1 Then
strIPNow2(i) = "00" & strIPNow2(i)
ElseIf Len(strIPNow2(i)) = 2 Then
strIPNow2(i) = "0" & strIPNow2(i)
End If
Next
Dim strIPOne2 As String = strIPNow2(0) & strIPNow2(1) & strIPNow2(2) & strIPNow2(3)

Dim strIPNow3() As String = Split(strEndIP, ".")
For i = 1 To 3
If Len(strIPNow3(i)) = 1 Then
strIPNow3(i) = "00" & strIPNow3(i)
ElseIf Len(strIPNow3(i)) = 2 Then
strIPNow3(i) = "0" & strIPNow3(i)
End If
Next
Dim strIPOne3 As String = strIPNow3(0) & strIPNow3(1) & strIPNow3(2) & strIPNow3(3)

If CLng(strIPOne1) >= CLng(strIPOne2) And CLng(strIPOne1) <= CLng(strIPOne3) Then
Return True
Else
Return False
End If
Catch ex As Exception
Return False
End Try
End Function
------解决方案--------------------
在java和javascript下面分别进行了编码。
比较了-1062731520和目标值3232235776的二进制编码:
- 111111010101111111111100000000
11000000101010000000000100000000
很有可能是编码损失了精度。

最后在《The Definitive Guide, 5th Edition 》中Section3.1中找到了答案:

The JavaScript number format allows you to exactly represent all integers between -9007199254740992 (-253) and 9007199254740992 (253), inclusive. If you use integer values larger than this, you may lose precision in the trailing digits. Note, however, that certain integer operations in JavaScript (in particular the bitwise operators described in Chapter 5) are performed on 32-bit integers, which range from -2147483648 (-231 ) to 2147483647 (231-1).
在位操作时只有32位的精度,所以楼主的函数出错了。

解决方案:
用以下函数取代与操作,即将
var startip = ipnum & masknum;