Socket throws an exception, although the port is free

I have the method, that should return true, if the socket port is free.

The implementation of the method:

  private def isPortFree(host: String, port: Int): Boolean = {
    import java.net.Socket
    try {
      // Socket try to open a REMOTE port
      new Socket(host, port).close()
      true
    } catch {
      case _: Exception => false
    }
  }

When the object gets initialized, then it throws an exception:

Connection refused (Connection refused) 

although the port is available. The host is “0.0.0.0”.

enter image description here

I am trying to validate, if the given port is free or not.

Leave a Reply

avatar
  Subscribe  
Notify of