如何决定使用哪个端口?

这是一个有点主观,因为没有 规矩这样说。每次我创建一个服务器时,我都会问自己: “什么是使用的最佳端口?”我猜 一个的答案是“任何,只要用户可以改变它。”那么,其他人如何决定如何选择默认端口呢?就我个人而言,我喜欢使用类似8000-如果它是 HTTP 相关的东西,我已经注意到这是一个非常普遍的趋势。但是如果8000已经在使用了呢?用8001?看起来有点特殊,我想也是。

很明显,我不是第一个问这个问题的人; IANA 有一个 港口号码列表... ... 这让我想到了未分配的范围(48620-49150)。我想我们真的应该使用这些,但是为什么没有更多的程序员这样做呢?您如何决定使用哪一个; 如果每个人都从 # 1开始,那么我们都将使用48620。

56498 次浏览

After a quick Google search to make sure it's clear, I generally just choose a number of personal significance.

You answered your own question? Pick any unassigned port and allow the user to change it.

During testing... always port #666 ;)

I think you've pretty much answered your question as much as is possible; there isn't really a strict rule you can follow here beyond what you've said. But generally:

  • Look at the IANA list and pick a port that's not in use.
  • Pick a port number that is easy to remember.
  • Don't fix the port number in your code. Some other product may have picked the same port as you and you never know when you'll have to co-exist on a server, so put the port number in a configuration file somewhere so it can be changed without a recompile if necessary. The ability to change port number can also be helpful for getting through firewalls without having to get them reconfigured. (You can always default to your chosen value if the configuration file doesn't exist.)
  • There is an argument that you don't want to pick something too high as you may conflict with the range used for ephemeral ports. It's not that likely that you'll get hit by this, but it's a hard problem to debug when it happens.

(And if you want a tip for picking memorable port numbers, I once worked with someone who remembered port numbers based around the telephone extensions of his co-workers.)

Some easy to remember and appropriately nerdy unassigned (per IANA) ports:

27182 (e)

31415 (pi)

60221 (avagadro's)

How about:

defaultPort = (new Random()).Next(48620, 49150);

I prefer this way: (python code following)

#!/usr/bin/env python3
import random as R
r = R.SystemRandom()
print([r.randrange(1024, 65535) for x in range(4)])

And then I pick the number which I like the most. Or course, change the range if you have some stricter limits of what are acceptable numbers.

I'd suggest never use a port that is a big number like 5 digits, as it might hit some other operation system processes and assigns the Ephemeral ports. You would start to get 'Already in use errors' due to its limitations.