• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to check if a port is available in Java?

 
ying lam
Ranch Hand
Posts: 85
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9214
9
Linux Mac OS X Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
ying lam
Ranch Hand
Posts: 85
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9214
9
Linux Mac OS X Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Managing sockets is a function of the OS, so I'd expect that the language wouldn't make much difference.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic