fix: improve QR direct connection reliability and speed

This commit is contained in:
zhy200308
2026-08-12 11:14:34 +08:00
parent 9c16cc1690
commit f9e25819ee
8 changed files with 152 additions and 13 deletions
@@ -0,0 +1,41 @@
package com.qft.optical
import java.net.URI
/** Pure IPv4 routing helpers kept Android-free so candidate selection is testable. */
object EndpointRouting {
fun onAnySubnet(
endpoints: List<String>,
expectedPort: Int,
localLinks: List<Pair<String, Int>>,
): List<String> {
val subnets = localLinks.mapNotNull { (address, prefix) ->
ipv4(address)?.let { it to prefix.coerceIn(0, 32) }
}
if (subnets.isEmpty()) return emptyList()
return endpoints.filter { endpoint ->
val uri = try { URI(endpoint) } catch (_: Exception) { return@filter false }
if (uri.scheme != "http" || uri.port != expectedPort) return@filter false
val candidate = ipv4(uri.host ?: return@filter false) ?: return@filter false
subnets.any { (local, prefix) -> sameSubnet(local, candidate, prefix) }
}.distinct()
}
private fun sameSubnet(a: Long, b: Long, prefix: Int): Boolean {
if (prefix == 0) return true
val mask = (0xFFFF_FFFFL shl (32 - prefix)) and 0xFFFF_FFFFL
return (a and mask) == (b and mask)
}
private fun ipv4(value: String): Long? {
val parts = value.split('.')
if (parts.size != 4) return null
var result = 0L
for (part in parts) {
val octet = part.toIntOrNull()?.takeIf { it in 0..255 } ?: return null
result = (result shl 8) or octet.toLong()
}
return result
}
}