Added IP.isLoopback

connection_type_change
nathan 2020-08-18 01:51:57 +02:00
parent b7dabe6db0
commit 32dc98470b
2 changed files with 49 additions and 2 deletions

View File

@ -90,6 +90,7 @@ object IPv4 {
private val private10 = toInt("10.0.0.0")
private val private172 = toInt("172.16.0.0")
private val private192 = toInt("192.168.0.0")
private val loopback172 = toInt("127.0.0.0")
/**
* Determines if this IP address is a private address or not.
@ -116,6 +117,22 @@ object IPv4 {
return isInRange(ipAsInt, private192, 16) || isInRange(ipAsInt, private172, 12) || isInRange(ipAsInt, private10, 8)
}
/**
* A loopback address is defined as
* 127.0.0.0/8
*/
fun isLoopback(ipAsString: String): Boolean {
return isInRange(toInt(ipAsString), loopback172, 8)
}
/**
* A loopback address is defined as
* 127.0.0.0/8
*/
fun isLoopback(ipAsInt: Int): Boolean {
return isInRange(ipAsInt, loopback172, 8)
}
/**
* Determine whether a given string is a valid CIDR IP address. Accepts only 1.2.3.4/24
*

View File

@ -250,8 +250,6 @@ object IPv6 {
} catch (e: UnknownHostException) {
throw RuntimeException(e) // Should never happen
}
// return NetUtil.getByName(ip, ipv4Mapped)
}
/**
@ -688,4 +686,36 @@ object IPv6 {
private fun inRangeEndExclusive(value: Int, start: Int, end: Int): Boolean {
return value >= start && value < end
}
/**
* IPv6 address reserved for loopback use is 0000:0000:0000:0000:0000:0000:0000:0001/128.
*
* This loopback address is so lengthy and can be further simplified as ::1/128, or just ::1
*
* /128 means EXACTLY this address
*/
fun isLoopback(ipAsString: String): Boolean {
var oneCount = 0
// can only be with one "1", and nothing else
ipAsString.forEach { char ->
when (char) {
':' -> {
// this is always ok
}
'1' -> {
oneCount++
if (oneCount > 1) {
return false
}
}
else -> {
// not OK
return false
}
}
}
return oneCount == 1
}
}