*
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
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: 8876
    
    8

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.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[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: 8876
    
    8

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?