-1

I have a Java program that was developed long ago. It's even in production now.

We basically try to create a socket as follows:

try {
    portnum = 4000;
    SSLContext sslctxt;
    SSLServerSocket serverSocket = (SSLServerSocket) sslctxt.getServerSocketFactory().createServerSocket(portnum);
} catch (IOException e)
{
//print exception
}

However, recently, when we deployed this on a Linux machine, we are always seeing the following exception thrown by the above code:

java.net.BindException: Address already in use (Bind failed)

I then did the following:

  1. Brought down all processes.
  2. Ran lsof -I:4000 and made sure there are no processes running on this port.
  3. I then started the above Java program.
  4. Now, lsof -I:4000 gives a PID and I confirmed that this PID belongs to the Java program I started in step 3. Basically it means that the Java program is able to open a socket on this port number.
  5. However, when I check the logs, I see that it is throwing the BindException I mentioned above.

What is surprising is that I have run this on multiple Linux machines before and never seen this happen. Any inputs on how I can debug this?

Thanks, Om

Omi
  • 976
  • 2
  • 20
  • 35
  • 1
    You really need to provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) The first thing that springs to mind is that code is called more than once. Possibly in a a loop even(?) – g00se Aug 30 '23 at 17:12
  • 1
    I'd be wary of some dangling instance of your program that is still running. `ps aux | grep java` (or your program name) to see if it's still up. If that program bound the port, then you clearly can't re-bind it in a new instance. Some information of the surrounding code would help too, especially since `//print exception` is outside the `catch` block in your example. – Rogue Aug 30 '23 at 17:17
  • Linux is known to reserve server ports for a short period of time after it was closed to avoid problems with still incoming packets for that port. So binding can fail even if no process is using it at the time you try to bind it. You can avoid that problem by setting the parameter to reuse the socket to true. – Robert Aug 30 '23 at 20:35
  • @Robert To reuse the *port.* – user207421 Aug 30 '23 at 22:43
  • @OP The situation you describe is impossible. *Ergo* it didn't happen. Examine your assumptions. – user207421 Aug 30 '23 at 22:44

0 Answers0