netcat 的 -q 选项到底有什么作用?

What exactly does the -q option of netcat do?

我有一个服务,我一直在代理后面调试它的行为。代理是一个黑盒子,但服务的行为可以用一个简单的 python 程序来模拟,如下所示:

#!/usr/bin/env python

import socket
import sys
import time

PORT = int(sys.argv[1] or 50007)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.bind(('', PORT))
    s.listen(1)
    conn, addr = s.accept()
    print('conn from %s' % (addr,))
    data = conn.recv(1024)
    time.sleep(1)
    conn.sendall(data)
finally:
    conn.close()
    s.close()

当我使用 netcat 直接连接到它时,我得到了预期的行为,即在使用换行符将一些任意文本发送到 stdin 后,服务器延迟一秒钟,回显它,然后关闭连接。但是,当我将此服务放在代理后面时,netcat 会立即以状态 0 退出,unless 我给它加上一些非零数字的 -q 选项,之后它的行为与直接连接。

引用我系统上 netcat 的联机帮助页:

-q      after EOF on stdin, wait the specified number of seconds and then quit.
        If seconds is negative, wait forever.

我要调试的是关于代理连接行为的不同,这会导致连接行为与 -q 选项不同,不幸的是,那个人页面对我帮助不大。如果它不是我的输入(从未收到我的 EOF),它指的是什么 "stdin" ?什么 EOF 是 -q 忽略了足够长的时间来接收代理数据,当没有代理中介连接时它不必忽略它?

编辑:根据要求,这里有一些示例调用,尽管它们是最基本的:

# after starting the example server on <someserver> with <someport

$ echo foo | nc <someserver> <someport>
foo
$

# the above, just with -q1 (no change)
$ echo foo | nc -q1 <someserver> <someport>
foo
$

# after starting the example server behind the blackbox proxy
$ echo foo | nc <someproxy> <someproxyport>
$

# same, but with -q
$ echo foo | nc -q1 <someproxy> <someproxyport>
foo
$

echo foo | netcat 在所有情况下都发送 EOF。不同的是 netcat 关闭其网络套接字的方式。

没有-q netcat 在收到EOF 后立即发送TCP FIN,关闭它的一半TCP 连接。这不是完全关闭连接,只是 an indication 不再发送数据。之后 netcat 一直从连接打印数据,直到它关闭。

普通服务器不处理来自 netcat 的 FIN,延迟,发送回显响应然后关闭连接的后半部分。

黑盒代理似乎通过立即关闭连接对来自客户端的 FIN 做出反应。这可能是某种服务器负载优化,例如,在有很多 Web 浏览器的情况下,这很有意义。

使用 -q netcat 不会发送 FIN,直到连接被服务器关闭或直到 -q 超时结束。

运行你在tcpdump -w下的四种情况,然后在Wireshark中加载捕获文件,跟随TCP流,看看区别。请注意,此 netcat 行为可能取决于 particular version,我确认 Ubuntu 16.04 + netcat-openbsd 1.105.