SoFunction
Updated on 2025-03-11

Android judging the legal implementation code of IP address

Android judging the legal implementation code of IP address

Yesterday, I searched online to determine whether the string in the text box is a legal IP address. I thought of a regular expression, but I was not familiar with this, so I searched for some information online and finally made it.

The specific code is very simple.

public boolean isIP(String addr)
    {
      if(() < 7 || () > 15 || "".equals(addr))
      {
        return false;
      }
      /**
        * Determine IP format and range
        */
      String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
      Pattern pat = (rexp);
      Matcher mat = (addr);
      boolean ipAddress = ();
      //=================== The bugs in the previous IP judgment are being judged      if (ipAddress==true){
        String ips[] = ("\\.");
        if(==4){
            try{
              for(String ip : ips){
                if((ip)<0||(ip)>255){
                  return false;
                }
              }
            }catch (Exception e){
              return false;
            }
          return true;
        }else{
          return false;
        }
      }
      return ipAddress;
    }
}

This code first uses regular expressions to determine whether it is legal. In fact, it is to determine whether the right three dots are separated from the string. However, the string is not judged whether it is a number. So I found another code to judge ip later. If the previous judgment is legal, then separate the string with dots, and then force it to number to determine whether it is between 0 and 255. If it is not satisfied or the forced conversion is reported, the false variable that is not ip is returned.

This completes the judgment of the legality of IP.

Thank you for reading, I hope it can help you. Thank you for your support for this site!