This time I stumble upon a very unusual problem, at least for me, UDP ports collision. A open source library that I used didn’t garantee that two different apps using that same library would have different UDP ports, so when I installed two of my prototypes one of them didn’t worked properly and unfortunately the library didn’t told me that was the problem it gave me a completely generic error.
Long story short, my first solution was to assign random ports but then I wondered if I could check available ports before falling back to random ports, so here it is.
Or if your prefer to determine the range of ports yourself
The downside of the second way is the possibility of running a forever check in the request method, we could use a retry counter to solve this but still I would rather rely on DatagramSocket finding an available port as stated in the docs:
“DatagramSocket() -> Constructs a datagram socket and binds it to any available port on the local host machine.”
Bear in mind that checking port doesn’t reserve it, so if a service requests that same port before you use it then you lost it.
There are ways to solve it and depends on how you want your software to behave, yet in general that approach has no problems in Android.