主要用于在js判断用户输入的一个ip段是否合法,如:192.168.1.11-192.168.1.134
实现代码一:
function ipToNumber(ip) { var num = 0; if(ip == "") { return num; } var aNum = ip.split("."); if(aNum.length != 4) { return num; } num += parseInt(aNum[0]) << 24; num += parseInt(aNum[1]) << 16; num += parseInt(aNum[2]) << 8; num += parseInt(aNum[3]) << 0; num = num > 0;//这个很关键,不然可能会出现负数的情况 return num; } function numberToIp(number) { var ip = ""; if(number <= 0) { return ip; } var ip3 = (number << 0 ) > 24; var ip2 = (number << 8 ) > 24; var ip1 = (number << 16) > 24; var ip0 = (number << 24) > 24 ip += ip3 + "." + ip2 + "." + ip1 + "." + ip0; return ip; }
实现代码二:
//IP转成整型 function _ip2int(ip) { var num = 0; ip = ip.split("."); num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]); num = num > 0; return num; } //整型解析为IP地址 function _int2iP(num) { var str; var tt = new Array(); tt[0] = (num > 24) > 0; tt[1] = ((num << 8) > 24) > 0; tt[2] = (num << 16) > 24; tt[3] = (num << 24) > 24; str = String(tt[0]) + "." + String(tt[1]) + "." + String(tt[2]) + "." + String(tt[3]); return str; }
以上就是完整代码,需要的朋友可以参考一下。