在Android的验证IPAndroid、IP

2023-09-13 23:41:02 作者:我懂、只是沉默不说

大家好, 我现在用简单的套接字机器人之间(如客户端)和PC(如服务器)的通信。我使用的EditText的IP地址。我想验证正在进入的EditText字段中的IP地址。可以请有一个人帮助我..我需要它。先谢谢了。

HI all, I am using simple socket communication between android(as client) and PC(as server). I am using EditText for Ip address. I want to Validate the IP address that is being entered in EditText field. Can please some one help me.. I am need of it. Thanks in advance.

推荐答案

如果你的目标API级别8,则可以使用的 Patterns.IP_ADDRESS 全球正则表达式。您可以直接包含这个表达式在你的项目,如果你的目标设备与Android< 2.2:

If you are targeting API Level 8, you can use the Patterns.IP_ADDRESS global regex. You may directly include this regex in your project if you target device 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
}