IP地址与十进制相互转换

1、IP 转成10进制

function ipToInt(ip){
    var REG =/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
    var xH = "",result = REG.exec(ip);
    if(!result) return -1;
    return (parseInt(result[1]) << 24 
        | parseInt(result[2]) << 16
        | parseInt(result[3]) << 8
        | parseInt(result[4]))>>>0;
}

例:

ipToInt("172.18.0.2");  // 2886860802

 

2、10进制转成 IP

function intToIp(INT){
    if(INT < 0 || INT > 0xFFFFFFFF){
        throw ("The number is not normal!");
    }
    return (INT>>>24) + "." + (INT>>16 & 0xFF) + "." + (INT>>8 & 0xFF) + "." + (INT & 0xFF);
}

例:

intToIp(2886860802); // 172.18.0.2

 

posted @ 2019-01-18 16:12  手指键盘摩擦  阅读(3191)  评论(0编辑  收藏  举报