Skip to content

Commit

Permalink
better local address fetching
Browse files Browse the repository at this point in the history
  • Loading branch information
DatL4g committed Jul 20, 2024
1 parent ea4de6b commit 6282421
Showing 1 changed file with 41 additions and 11 deletions.
52 changes: 41 additions & 11 deletions src/jvmMain/kotlin/dev/datlag/k2k/NetInterface.jvm.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,55 @@ package dev.datlag.k2k
import dev.datlag.tooling.scopeCatching
import kotlinx.collections.immutable.ImmutableSet
import kotlinx.collections.immutable.toImmutableSet
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface

actual object NetInterface {
actual fun getAddresses(): ImmutableSet<String> {
return NetworkInterface.getNetworkInterfaces().toList().filterNotNull().mapNotNull {
scopeCatching {
if (it.isLoopback || !it.isUp) {
return@scopeCatching null
}
return scopeCatching {
NetworkInterface.getNetworkInterfaces().toList().filterNotNull().mapNotNull {
scopeCatching loop@{
if (it.isLoopback || !it.isUp) {
return@loop null
}

it.interfaceAddresses.mapNotNull { all ->
all?.broadcast?.hostAddress?.ifBlank { null }
}
}.getOrNull()
}.flatten().toImmutableSet()
it.interfaceAddresses.mapNotNull { all ->
all?.broadcast?.hostAddress?.ifBlank { null }
}
}.getOrNull()
}.flatten()
}.getOrNull().orEmpty().toImmutableSet()
}

actual fun getLocalAddress(): String {
return InetAddress.getLocalHost().hostAddress
val allAvailable = mutableSetOf<String>()
val interfaces = scopeCatching {
NetworkInterface.getNetworkInterfaces()
}.getOrNull() ?: return InetAddress.getLocalHost().hostAddress

for (inter in interfaces) {
if (inter == null) {
continue
}

for (inet in inter.inetAddresses) {
if (inet == null) {
continue
}

if (!inet.isLoopbackAddress && inet is Inet4Address) {
inet.hostAddress?.ifBlank { null }?.let(allAvailable::add)
}
}
}

if (allAvailable.isEmpty()) {
return InetAddress.getLocalHost().hostAddress
}

return allAvailable.singleOrNull() ?: scopeCatching {
InetAddress.getLocalHost().hostAddress?.ifBlank { null }
}.getOrNull() ?: allAvailable.first()
}
}

0 comments on commit 6282421

Please sign in to comment.