Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TCP 和 UDP 可以使用同一个端口吗? #303

Open
BenXiangYangGuang opened this issue Dec 10, 2024 · 0 comments
Open

TCP 和 UDP 可以使用同一个端口吗? #303

BenXiangYangGuang opened this issue Dec 10, 2024 · 0 comments

Comments

@BenXiangYangGuang
Copy link

操作系统和网络协议栈通过以下方式区分端口上运行的是 TCP 应用服务还是 UDP 应用服务:

1. 协议标识

每个网络通信套接字(socket)都由以下四元组唯一标识:

  • IP 地址
  • 端口号
  • 传输层协议类型(TCP 或 UDP)
  • 方向(客户端/服务端)

操作系统通过传输层协议类型区分同一端口号属于 TCP 还是 UDP。

2. 套接字绑定

  • 当应用程序启动服务时,会通过系统调用(如 bind)绑定某个端口,并显式指定是使用 TCP 或 UDP。
  • 操作系统会将端口号和协议类型(TCP/UDP)一起注册。
    • 若使用 TCP,则在 TCP 的监听队列中登记。
    • 若使用 UDP,则在 UDP 的套接字表中登记。

3. 数据包头信息

当网络数据包到达服务器时:

  • 传输层协议类型:数据包的 IP 报头中包含一个字段,指示这是 TCP 还是 UDP 包。
  • 目的端口号:根据协议类型,操作系统在对应的协议(TCP 或 UDP)的端口表中查找,找到对应的应用服务。

4. 应用层的处理

  • TCP 应用:需要建立连接(如握手)后才能接收和处理数据。
  • UDP 应用:无需连接,直接通过端口接收数据。

总结

应用服务是否为 TCP 或 UDP,完全取决于其在绑定端口时指定的协议类型,而区分的关键在于操作系统管理的协议类型和端口号表

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant