How do you validate an IP address on Android?

前端 未结 3 630
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 02:06

I am using simple socket communication between Android (as the client) and PC (as the server). I am having the user input the IP address into an EditText field

相关标签:
3条回答
  • 2020-12-24 02:25

    API Level 8+:

    You can use the Patterns.IP_ADDRESS global regex.

    API Level 1-7:

    You may directly include this regex in your project if you target devices with android < 2.2:

    private static final Pattern IP_ADDRESS
        = Pattern.compile(
            "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]"
            + "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]"
            + "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
            + "|[1-9][0-9]|[0-9]))");
    Matcher matcher = IP_ADDRESS.matcher("127.0.0.1");
    if (matcher.matches()) {
        // ip is correct
    }
    
    0 讨论(0)
  • 2020-12-24 02:39
    Patterns.IP_ADDRESS.matcher(url).matches();
    
    0 讨论(0)
  • 2020-12-24 02:43

    To check the IP as it's being entered you might want to use this instead:

    private static final Pattern PARTIAl_IP_ADDRESS =
              Pattern.compile("^((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])\\.){0,3}"+
                               "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])){0,1}$"); 
    
    ipEditText.addTextChangedListener(new TextWatcher() {                       
        @Override public void onTextChanged(CharSequence s, int start, int before, int count) {}            
        @Override public void beforeTextChanged(CharSequence s,int start,int count,int after) {}            
    
        private String mPreviousText = "";          
        @Override
        public void afterTextChanged(Editable s) {          
            if(PARTIAl_IP_ADDRESS.matcher(s).matches()) {
                mPreviousText = s.toString();
            } else {
                s.replace(0, s.length(), mPreviousText);
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题