如何找到任意一台PC的端口号?
目前,我正在用 C 语言实现 TCP 客户端/服务器。其中,我发现我可以给出任何随机数作为我的 PC 的端口号。这是正确的程序吗?或者我的电脑有标准端口号吗?
Currently, I'm working on TCP client/server implementation in C. In that, I found that I can give any random number as a port number for my PC. Is it correct procedure? Or is there any standard port number for my PC?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的问题是是否可以提供任何端口号让服务器监听,
那么你就错了,1024以下的TCP/IP端口号是特殊的,普通用户不允许在其上运行服务器,你可以使用非特权端口(端口> 1024)。只需使用 netstat 确保任何其他应用程序尚未使用该端口(1024 以上)
If your question is whether you can give any port number to have your server listening to,
then you are thinking wrong, TCP/IP port numbers below 1024 are special in that normal users are not allowed to run servers on them, you can use non-privileged ports(ports > 1024). just make sure that any other application is not already using that port (above 1024) using netstat
我不知道标准,但我说不是。至少,我不喜欢那样做。
您可以通过解析 netstat 等程序的输出来检查占用的端口,并避免使用它们。您还可以使用在一个端口上尝试连接并在失败时尝试另一个端口的方法。除非你真的很不幸,否则你应该在第二次尝试时获得有效的端口。
您应该使用 49152–65535 范围内的端口。低于 49152 的端口被保留/注册。
I don't know the standard, but I say it's not. At least, I don't like to do it like that.
You can check occupied ports by parsing the outputs of programs like
netstat
and avoid using those. You can also use the method that attempts connecting on one port, and upon failure, tries another port. Unless you're really really unlucky, you should get a valid port on second try.You should use ports within the ranges of 49152–65535. Ports below 49152 are reserved/registered.
基本上,您可以使用任何端口(只要有足够的访问权限)。但服务器和客户端必须在端口上达成一致,并且该端口不应已被其他应用程序使用。
因此,许多端口已经预留给特殊应用。 80 用于 HTTP,22 用于 SSH,依此类推。文件
/etc/services
提供了更详细的信息。端口号 0-1023 称为“众所周知的端口”,端口号 1024-49151 称为“注册端口”(不是全部端口,但您明白了)。
Basically, you can use any port (given sufficient access rights). But server and client have to agree on the port, and it should not be already used by another application.
Hence, many ports are already reserved for special applications. 80 is for HTTP, 22 is for SSH and so on. The file
/etc/services
gives more detailed information.Port numbers 0-1023 are called Well Known Ports, numbers 1024-49151 are called Registered Ports (not all of them are, but you get the idea).