IP-addresses stored as int results in overflow?

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

提交回复
热议问题