UPDATE:
Your answers to the questions in the comments lead me to the thought that the application just opens more connections "at the same time" than allowed by the system. I quoted "at the same time" because as I wrote below, even if the application closes the connection, the port will be blocked by the TCP/IP stack for some time. I have to admit that I don't know whether the OS counts this as "used by the application" for that time.
Anyways your applications usually are not allowed to open all theoretically available ports at the same time.
If you use Linux or another Unix based OS (eg. MacOS), the number of open connections is counted against the open file descriptors. (On my Ubuntu system there is a limit of 1024 concurrently opened files.)
When you start the process from your terminal from bash
, you can look at the ulimit
command and find the limit with ulimit -a
. For system-wide limitations, have a look at this SO answer to Increasing the maximum number of TCP/IP connections in Linux
For windows systems I did only a bit of search but cannot verify this, I found this article for Microsoft Windows 10: Troubleshoot port exhaustion issues
Original:
You will have to look at the stack trace of the exception to find out where it is triggered - maybe you can find the right class to enable logging for.
But it is not guaranteed that an application logs the network address it is trying to open.
When you describe that after some attempts it works again, you can try to find out with the command netstat
what ports are actually opened, and also which processes use them.
Look out for the state "TIME_WAIT": such connections are actively closed, but the networking stack still doesn't reuse the port as "old" packages from the recently opened connection could be on the way to the receiver. After a configured timeout, that port is then reusable again.
Find more details about this state in this SO question and its answers.
You also could try to attach a debugger to the active application, probably best with a built in decompiler or a plugin for that (usually IDEs like IntelliJ IDEA are able to do that) so you can set a breakpoint to the call of the method that throws the exception and inspect its parameters to find out about the port.