如何为 Java 套接字指定端口范围? [英] How do you specify a port range for Java sockets?
问题描述
在 Java 中,您可以将数字零作为 Socket 或 DatagramSocket 构造函数的单个参数.Java 然后将该 Socket 绑定到一个空闲端口.是否可以将端口查找限制在特定范围内?
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?
推荐答案
Hrm,看完文档后,我认为你不能.您可以绑定到任何端口,如果不可接受则重新绑定,或者重复绑定到您范围内的端口直到成功.第二种方法将是最有效"的.
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 :/
这篇关于如何为 Java 套接字指定端口范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!