File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Sockets and Internet Protocols and the fly likes How to check if a port is available in Java? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "How to check if a port is available in Java?" Watch "How to check if a port is available in Java?" New topic
Author

How to check if a port is available in Java?

ying lam
Ranch Hand

Joined: May 17, 2004
Posts: 85
Hi,

I have this piece of code which checks if a port is available:



However, sometimes this function returns true (i.e. the port is availble), but when a external C program opens the same port, it fails to open.

I wonder if Java releases the port immediately in OS level when i do this 'srv.close()'. Otherwise, I don't see why another external C programs fail to open the same port.

Or am I missing anything?

Thank you.
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8997
    
    9

After a socket is bound and released, the operating system will spend some time doing cleanup work. In netstat, these sockets will show up in the TIME_WAIT state and will not be available for binding. See socket states for more.


[How To Ask Questions On JavaRanch]
ying lam
Ranch Hand

Joined: May 17, 2004
Posts: 85
Thanks. But will the time for required for OS to do cleanup work of releasing sockets if I do everything in C?
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8997
    
    9

Managing sockets is a function of the OS, so I'd expect that the language wouldn't make much difference.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to check if a port is available in Java?