java TCP 允许的端口范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12889702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:39:17  来源:igfitidea点击:

Allowed Port Range for TCP

javatcp

提问by Mike G

I am trying to generate a random port number for a TCP connection. From : http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbersI know that the range of ports is from 1024 to 49151 are not reserved, but some of them are UDP only, how can I generate only valid TCP port numbers?

我正在尝试为 TCP 连接生成一个随机端口号。来自:http: //en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers我知道端口的范围是从 1024 到 49151 不是保留的,但其中一些只是 UDP,我怎样才能只生成有效的 TCP 端口号?

回答by Eric

If you bind to port 0, the OS will select a valid, not-in-use port.

如果绑定到端口 0,操作系统将选择一个有效的、未使用的端口。

If you need random as opposed to arbitrary, anything from 49152–65535 should be safe for automatic use like this, so just select a random number within that range. (you may have to retry if that port turns out to be in use, however.)

如果您需要随机而不是任意,那么 49152-65535 之间的任何内容对于像这样自动使用应该是安全的,因此只需在该范围内选择一个随机数。(但是,如果该端口正在使用中,您可能必须重试。)