When sending a datagram using UDP, is it possible ...
# ktor
s
When sending a datagram using UDP, is it possible to determine the port it's sent from?
I'd like for this function to return the outgoing port: https://github.com/sproctor/ONVIFCameraAndroid/blob/master/onvifcamera/src/commonMain/kotlin/com/seanproctor/onvifcamera/OnvifDevice.kt#L177 The SOAP discovery spec says that the service should respond on the port that the packet originated from.
a
You can use the
address
property of an incoming
Datagram
:
Copy code
fun main() = runBlocking {
    val selectorManager = SelectorManager(<http://Dispatchers.IO|Dispatchers.IO>)
    val serverSocket = aSocket(selectorManager).udp().bind(InetSocketAddress("127.0.0.1", 9002))

    for (datagram in serverSocket.incoming) {
        serverSocket.outgoing.send(
            Datagram(
                BytePacketBuilder().apply { append("Hello client") }.build(),
                datagram.address
            )
        )
    }
}
s
I'm trying to write the client. There's a server listening on port 3702. I need to broadcast 3702 and the server will respond on the source port of the broadcast.
I've re-written the probe as a typical socket connection, but it doesn't receive any response (despite that I can see there was a response monitoring network traffic) https://github.com/sproctor/ONVIFCameraAndroid/blob/master/onvifcamera/src/commonMain/kotlin/com/seanproctor/onvifcamera/OnvifDevice.kt#L146
The probe gets sent to IP 239.255.255.250 (per the SOAP discovery spec) and the response is from 192.168.0.209 (the IP address of the device I'm probing) or multiple IP addresses if multiple devices respond.
Thanks, I figured it out. Your comment eventually led me in the correct direction. I needed to use the
localAddress
from the socket sending the probe. you can see the final result on github.
176 Views