IP-addresses stored as int results in overflow?

后端 未结 11 458
無奈伤痛
無奈伤痛 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:17

    IP Addresses in the V4 space are unsigned 32 bit numbers, hence the IP address of FF.FF.FF.FF is 2^32 and cannot be greater then that number. Please see:

    This stack overflow article on the same subject

    To turn that number back into an IP address you must break the number down into its 4 parts since each byte is one octet of the address so convert the number to hex and then parse out each pair. You may or may not have to add a leading zero for the first octet.

    Additionally you may have to deal with byte order of the integer ( endien issues ) but since most systems are intel based these days you might not have to deal with that.

    0 讨论(0)
  • 2021-02-02 13:25

    You shifted left to get the original number - which is just 4 sets of bits regardless of the sign.

    Shift right to get back to the IP. Doesn't matter what the sign is.

    0 讨论(0)
  • 2021-02-02 13:27
    const ip2int = (x) => (x.split('.').reduce((a, v) => ((a << 8) + (+v)), 0) >>> 0);
    
    0 讨论(0)
  • 2021-02-02 13:29

    The result of the "<<" operator is always a signed, 32-bit integer, as per the spec.

    When you shift back, use ">>>" to do an unsigned right shift.

    0 讨论(0)
  • 2021-02-02 13:30

    You might also find this pattern useful:

    ip.toLong = function toInt(ip){
      var ipl=0;
      ip.split('.').forEach(function( octet ) {
          ipl<<=8;
          ipl+=parseInt(octet);
      });
      return(ipl >>>0);
    };
    
    ip.fromLong = function fromInt(ipl){
      return ( (ipl>>>24) +'.' +
          (ipl>>16 & 255) +'.' +
          (ipl>>8 & 255) +'.' +
          (ipl & 255) );
    };
    

    If you're using something like node.js where you can add functionality through something like Npm then you can simply do:

    npm install ip
    

    To get that functionality from the source which is here:
    https://github.com/indutny/node-ip/blob/master/lib/ip.js

    You will also get a bunch of other IP utility functions with that.

    0 讨论(0)
提交回复
热议问题