IP-addresses stored as int results in overflow?

后端 未结 11 471
無奈伤痛
無奈伤痛 2021-02-02 12:27

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

11条回答
  •  被撕碎了的回忆
    2021-02-02 13:11

    I revised Evan's final answer a bit, particularly dot2num. It functions the same but might be more readable and is marginally slower.

    function ip2num(ip) {
        var parts = ip.split('.');
    
        var num = 0;
        num += d[0] * Math.pow(2, 24);
        num += d[1] * Math.pow(2, 16);
        num += d[2] * Math.pow(2, 8);
        num += d[3];
    
        return num;
    }
    
    function num2ip(num) {
        var ip = num % 256;
    
        for (var i=3; i > 0; i--) { 
            num = Math.floor(num / 256);
            ip = num % 256 + '.' + ip;
        }
    
        return ip;
    }
    

提交回复
热议问题