diff --git a/app/src/commonMain/kotlin/com/aerotoss/discovery/TcpDiscovery.kt b/app/src/commonMain/kotlin/com/aerotoss/discovery/TcpDiscovery.kt index 5c0f376..a770627 100644 --- a/app/src/commonMain/kotlin/com/aerotoss/discovery/TcpDiscovery.kt +++ b/app/src/commonMain/kotlin/com/aerotoss/discovery/TcpDiscovery.kt @@ -113,7 +113,7 @@ class TcpDiscovery : DiscoveryManager { deviceName = deviceName, deviceType = "desktop", servicePort = servicePort, - hostAddress = sock.localAddress.hostAddress + hostAddress = findNetworkAddress() ) output.write(json.encodeToString(response)) output.newLine() @@ -123,6 +123,24 @@ class TcpDiscovery : DiscoveryManager { } catch (_: Exception) {} } + private fun findNetworkAddress(): String { + return try { + NetworkInterface.getNetworkInterfaces()?.toList() + ?.filter { it.isUp && !it.isLoopback } + ?.flatMap { it.inetAddresses.toList() } + ?.filterIsInstance() + ?.firstOrNull { isPrivate(it) } + ?.hostAddress ?: "127.0.0.1" + } catch (_: Exception) { "127.0.0.1" } + } + + private fun isPrivate(addr: java.net.InetAddress): Boolean { + val bytes = addr.address + return (bytes[0].toInt() and 0xFF == 192 && bytes[1].toInt() and 0xFF == 168) || + (bytes[0].toInt() and 0xFF == 10) || + (bytes[0].toInt() and 0xFF == 172 && (bytes[1].toInt() and 0xFF in 16..31)) + } + private fun sendBroadcast(socket: DatagramSocket, servicePort: Int) { try { val message = "AEROTOSS:$TCP_PORT:$servicePort:$deviceId:$deviceName"