Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you specify a port range for Java sockets?

In Java you can give the number zero as a single parameter for the Socket or DatagramSocket constructor. Java binds that Socket to a free port then. Is it possible to limit the port lookup to a specific range?

like image 274
Roland Schneider Avatar asked Sep 22 '08 15:09

Roland Schneider


2 Answers

Hrm, after reading the docs, I don't think you can. You can either bind to any port, then rebind if it is not acceptable, or repeatedly bind to a port in your range until you succeed. The second method is going to be most "efficient".

I am uneasy about this answer, because it is... inelegant, yet I really can't find anything else either :/

like image 85
freespace Avatar answered Oct 21 '22 20:10

freespace


Binding the socket to any free port is (usually) a feature of the operating system's socket support; it's not specific to java. Solaris, for example, supports adjusting the ephemeral port range through the ndd command. But only root can adjust the range, and it affects the entire system, not just your program.

If the regular ephemeral binding behavior doesn't suit your needs, you'll probably have to write your own using Socket.bind().

like image 29
Kenster Avatar answered Oct 21 '22 21:10

Kenster