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 and I want to validate the IP address. How do you validate an IP address on Android?
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 and I want to validate the IP address. How do you validate an IP address on Android?
Reading description about Patterns.IP_ADDRESS I've seen that it's will be deprecated (on API 31) and needs use another function (InetAddresses.isNumericAddress) for check ip adress.
The result:
fun isIpValid(ip: String): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
InetAddresses.isNumericAddress(ip)
} else {
Patterns.IP_ADDRESS.matcher(ip).matches()
}
}
The solution in Kotlin to find a Valid IP:
import java.util.regex.*;
...
...
fun isValidIPAddress(ip:String):Boolean {
// Regex for digit from 0 to 255
val reg0To255 = ("(\\d{1,2}|(0|1)\\" + "d{2}|2[0-4]\\d|25[0-5])")
// regex 0 To 255 followed by a dot, 4 times repeat
// validation an IP address.
val regex = (reg0To255 + "\\."
+ reg0To255 + "\\."
+ reg0To255 + "\\."
+ reg0To255)
val p = Pattern.compile(regex)
val m = p.matcher(ip)
return m.matches()
}
val inputIP = "127.1.1.775"
println("Input: " + inputIP)
println("Output: " + isValidIPAddress(inputIP))
...
...
Input: 127.1.1.055 Output: true
Input: 127.ip.1.75 Output: false
Input: 127.201.1.775 Output: false