javascript implementation to verify IP address and other relevant information code

  • 2020-06-07 04:02:25
  • OfStack

This code is extracted from the personal project, should be able to calculate on the IP is quite comprehensive and effective related information verification code, used for front-end verification


/* ****************** */
/*  judge IP Whether the address is legal  */
var judgeIpIsLegal = function(ipAddr){
  var regIps = /^(((25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|[0-9])\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|[0-9]))$/;
  return regIps.test(ipAddr);
}
/* IP Address conversion to 2 Base string  */
/*  Such as: 172.16.4.235 --> 10101100000100000000010011101011 */
var praseIpToBinary = function(ipAddress){
  var numArray = ipAddress.split(".");
  if(numArray.length != 4){
    alert(" The input of IP wrong ");
    return;
  }
  var returnIpStr = "";
  for (var i = 0; i < 4; i++) {
    var curr_num = numArray[i];
    var number_Bin = parseInt(curr_num);
    number_Bin = number_Bin.toString(2);
    var iCount = 8-number_Bin.length;
    for (var j = 0; j < iCount; j++) {
      number_Bin = "0"+number_Bin;
    }
    returnIpStr += number_Bin;
  }
  return returnIpStr;
}
/*  Determines whether the subnet mask is valid  */
/*  The subnet mask must be  1  and  0 Composed of continuous 1 Period of   Such as  11110000 */
var judgeSubnetMask = function(ipAddress){
  var binaryIpString = praseIpToBinary(ipAddress).toString();
  var subIndex = binaryIpString.lastIndexOf("1")+1;
  var frontHalf = binaryIpString.substring(0,subIndex);
  var backHalf = binaryIpString.substring(subIndex);
  if(frontHalf.indexOf("0") != -1 || backHalf.indexOf("1") != -1){
    return false;
  }else{
    return true;
  }
}
/*  two IP Address for   with   operation   Returns the result  */
/*  This function is mainly used for implementation  IP Address and subnet mask   To get the current IP Address of the IP addresses  */
/*  Verify that the gateway address entered is valid  */
var getIPsAndResult = function(ipAddr1,ipAddr2){
  var ipArray1 = ipAddr1.split(".");
  var ipArray2 = ipAddr2.split(".");
  var returnResult = "";
  if(ipArray1.length != 4 || ipArray2.length != 4 ){
    alert(" The input of IP wrong ");
    return;
  }
  for (var i = 0; i < 4; i++) {
    var number1 = parseInt(ipArray1[i]);
    var number2 = parseInt(ipArray2[i]);
    returnResult += number1&number2;
    if(i<3){
      returnResult += ".";
    }
  }
  return returnResult;
}
/*  Determine if the gateway address is valid  */
var judgeGatewayResult = function(ipAddr,subnetMask,gateway){
  var andResult1 = getIPsAndResult(ipAddr,subnetMask);
  var andResult2 = getIPsAndResult(gateway,subnetMask);
  if(andResult1 == andResult2){
    return true;
  }else{
    return false;
  }
}

This is the end of this article, I hope you enjoy it.


Related articles: