Skip to content

Commit

Permalink
resolve hostname
Browse files Browse the repository at this point in the history
  • Loading branch information
DatL4g committed Nov 16, 2024
1 parent 44c3286 commit f5afb45
Show file tree
Hide file tree
Showing 5 changed files with 14 additions and 3 deletions.
2 changes: 2 additions & 0 deletions src/appleMain/kotlin/dev/datlag/k2k/NetInterface.apple.kt
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,6 @@ actual object NetInterface {
freeifaddrs(ifa.ptr)
return address ?: ""
}

actual fun resolve(name: String): String = name
}
1 change: 1 addition & 0 deletions src/commonMain/kotlin/dev/datlag/k2k/NetInterface.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ expect object NetInterface {
// udp, no isLoopback, broadcastAddress is not null
fun getAddresses(): ImmutableSet<String>
fun getLocalAddress(): String
fun resolve(name: String): String
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ internal class DiscoveryServer : AutoCloseable {
val host = Constants.protobuf.decodeFromByteArray<Host>(receivedPacket).apply {
val inetSocketAddress = datagram.address as InetSocketAddress

this.hostAddress = inetSocketAddress.hostname
this.hostAddress = NetInterface.resolve(inetSocketAddress.hostname)
}

hosts.update {
Expand Down
6 changes: 4 additions & 2 deletions src/jvmMain/kotlin/dev/datlag/k2k/NetAddress.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface

data class NetAddress(
data class NetAddress internal constructor(
val address: String?,
val isLoopback: Boolean,
val isVirtual: Boolean,
Expand All @@ -33,7 +33,9 @@ data class NetAddress(
up: Boolean
) : this(
address = scopeCatching {
inetAddress.hostAddress?.trim()
scopeCatching {
InetAddress.getByName(inetAddress.hostAddress?.trim())
}.getOrNull()?.hostAddress?.ifBlank { null } ?: inetAddress.hostAddress?.trim()
}.getOrNull()?.ifBlank { null },
isLoopback = loopback ?: scopeCatching {
inetAddress.isLoopbackAddress
Expand Down
6 changes: 6 additions & 0 deletions src/jvmMain/kotlin/dev/datlag/k2k/NetInterface.jvm.kt
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,10 @@ actual object NetInterface {
?: candidates.firstNotNullOfOrNull { it.address }
?: InetAddress.getLocalHost().hostAddress
}

actual fun resolve(name: String): String {
return scopeCatching {
InetAddress.getByName(name).hostAddress
}.getOrNull()?.ifBlank { null } ?: name
}
}

0 comments on commit f5afb45

Please sign in to comment.