存储为int的IP地址会导致溢出? [英] IP-addresses stored as int results in overflow?
问题描述
我正在node.js中编写聊天服务器,我想将连接用户的IP地址存储在mysql数据库中作为(无符号)整数。
我编写了一个javascript方法将ip-address转换为字符串为整数。然而,我得到了一些奇怪的结果。
I'm writing a chat-server in node.js, and I want to store connected users IP-addresses in a mysql database as (unsigned) integers. I have written a javascript method to convert an ip-address as string to an integer. I get some strange results however.
这是我的代码:
function ipToInt(ip) {
var parts = ip.split(".");
var res = 0;
res += parseInt(parts[0], 10) << 24;
res += parseInt(parts[1], 10) << 16;
res += parseInt(parts[2], 10) << 8;
res += parseInt(parts[3], 10);
return res;
}
当我运行时将方法调用为 ipToInt( 192.168.2.44);
我得到的结果是 -1062731220
。
好像发生了溢出,这很奇怪,因为预期的输出(3232236076)
在javascript(2 ^ 52)的数字范围内。
When I run call the method as ipToInt("192.168.2.44");
the result I get is -1062731220
.
It seems like an overflow has occurred, which is strange, because the expected output (3232236076)
is inside the number range in javascript (2^52).
当我以二进制形式检查 -1062731220
时,我可以看到 3232236076
被保留,但填充了前导1。
When I inspect -1062731220
in binary form, I can see the 3232236076
is preserved, but filled with leading 1's.
我不确定,但我认为问题在于有符号与无符号整数。
I'm not sure, but I think the problem is with signed vs. unsigned integers.
你们任何人都能解释一下发生了什么吗?
可能如何解析 -1062731220
回到字符串ip?
Can any of you explain what is going on?
And possibly how to parse -1062731220
back to an string ip?
推荐答案
为什么转换后的IP为负?
这不是溢出。 IP地址的第一部分是192,它以二进制形式转换为11000000。然后你将它一直向左移动。如果32位数字的最左侧位置有1,则为负数。
It's NOT an overflow. The first part of your IP address is 192 which converts to 11000000 in binary. You then shift that all the way to the left. When there is a 1 in the leftmost position of a 32 bit number, it's negative.
如何转换回字符串?
执行与从字符串转换相反的操作。右移(和掩码)!
Do the same thing you did to convert from a string but in reverse. Shift right (and mask)!
function intToIP(int) {
var part1 = int & 255;
var part2 = ((int >> 8) & 255);
var part3 = ((int >> 16) & 255);
var part4 = ((int >> 24) & 255);
return part4 + "." + part3 + "." + part2 + "." + part1;
}
为什么重新发明轮子?来自Google:
或者,您可以使用我在此处找到的内容:
http://javascript.about.com/library/blipconvert.htm
OR, you can use what I found here:
http://javascript.about.com/library/blipconvert.htm
function dot2num(dot)
{
var d = dot.split('.');
return ((((((+d[0])*256)+(+d[1]))*256)+(+d[2]))*256)+(+d[3]);
}
function num2dot(num)
{
var d = num%256;
for (var i = 3; i > 0; i--)
{
num = Math.floor(num/256);
d = num%256 + '.' + d;
}
return d;
}
这篇关于存储为int的IP地址会导致溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!