【问题标题】:Rules that allow for local port reuse by an application允许应用程序重用本地端口的规则
【发布时间】:2012-01-21 07:31:36
【问题描述】:

对于具有以下结构的 TCP 服务器:

main(){
    socket();
    bind();
    listen();
    while(1){
       accept();
       fork();
       if(child)
          Process;
    }
}

它为每个客户端创建一个新的套接字,并使用相同的端口与所有客户端通信。因此,所有套接字都绑定到同一个端口。

我在阅读内核代码(2.6.33.5)时遇到了comments

48/* There are a few simple rules, which allow for local port reuse by
49 * an application.  In essence:
50 *
51 *      1) Sockets bound to different interfaces may share a local port.
52 *         Failing that, goto test 2.
53 *      2) If all sockets have sk->sk_reuse set, and none of them are in
54 *         TCP_LISTEN state, the port may be shared.
55 *         Failing that, goto test 3.
56 *      3) If all sockets are bound to a specific inet_sk(sk)->rcv_saddr local
57 *         address, and none of them are the same, the port may be
58 *         shared.
59 *         Failing this, the port cannot be shared.
60 *

那么,对于上面的 TCP 服务器,是它匹配的第三条规则吗?

【问题讨论】:

  • 不管linux的实现如何,一个TCP连接都是通过五元组来区分的:(protocol, local addr, local port, remote addr, remote port)。

标签: c linux sockets linux-kernel


【解决方案1】:

这个游戏有 1 加 N 个插槽。

1 侦听套接字,已传递给bind()listen()。只有这个套接字绑定到服务器监听的端口。

2 由连接到服务器的 N 个“进程”客户端创建的所有 N 个 已连接套接字,并由 accept() 返回。这些套接字提供与客户端的连接。此类套接字监听套接字那样监听。

您引用的规则仅适用于侦听套接字

因此,如果您只运行一个服务器实例,则第三条规则适用,因为它bind()s 只有一个套接字到服务器端口上的listen()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 2018-02-07
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多