netcat发送额外的“X”UDP数据包

时间:2016-02-18 15:34:16

标签: python sockets netcat

here窃取我设置了一个小型Python脚本,该脚本侦听端口并打印出它收到的所有UDP数据包:

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024)
    print "received message:", repr(data)

现在我使用netcat将数据发送到此脚本。这是我的命令行。

echo -e "foo:1|c" | netcat -v -u localhost 5005

以下是Python的输出:

received message: 'X'
received message: 'X'
received message: 'X'
received message: 'X'
received message: 'X'
received message: 'foo:1|c\n'

前四个左右的“X”线以大约一秒的间隔到达,然后最后两条线大致同时到达。

我的问题是:这些额外的“X”数据包来自哪里,如果来源是netcat,那么我如何阻止netcat发出它们?我相信这是BSD的netcat

3 个答案:

答案 0 :(得分:6)

  

我相信这是BSD的netcat。

我有同样的问题,当我做nc --version时,我确实看到了:

  

这是来自netcat-openbsd包的nc。 netcat-traditional包中提供了另一种nc。

传统观点认为BSD是“更好”的版本(见What are the differences between netcat-traditional and netcat-openbsd?

但无论如何,BSD源是人们必须寻找“X”实际来自哪里的相关代码的地方。你不必太难看!

http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/nc/netcat.c?rev=1.177

吸烟枪是一种功能udptest()

/*
 * udptest()
 * Do a few writes to see if the UDP port is there.
 * Fails once PF state table is full.
 */
int
udptest(int s)
{
    int i, ret;

    for (i = 0; i <= 3; i++) {
        if (write(s, "X", 1) == 1)
            ret = 1;
        else
            ret = -1;
    }
    return (ret);
}

调用此函数的条件是设置vflag(详细程度)或zflag(端口扫描标记):

if (vflag || zflag) {
    /* For UDP, make sure we are connected. */
    if (uflag) {
        if (udptest(s) == -1) {
            ret = 1;
            continue;
        }
    }
    ...

关于基本原理为什么-v开关会开始在UDP端口投掷随机数据,我猜想那些使用-v的人想要他们可以得到的每一点信息。因此,获得关于连接的早期和声音错误消息的权衡是值得的,以帮助处于调试情况的人。

但即便如此,我的意见是,不要发送神秘的"X",而是发送像"NETCAT UDP PING DUE TO -V OPTION"这样的东西会更好。 : - /

答案 1 :(得分:2)

由于我无法确定的原因,X选项会将-v个数据包发送到nc。试试这个:

echo -e "foo:1|c" | netcat -u localhost 5005

答案 2 :(得分:0)

使用counterFile = open("counter.txt","r") #counter.txt stores the number of times code has been run. Just create this file manually counter = counterFile.read() if(len(counter) == 0): counter = 0 else: counter = int(counter) counterFile.close() exp = 0 with open ('test.txt','r') as b: lines = b.readlines() with open('test.txt','w') as b: for i,line in enumerate(lines): print i if i == exp+counter: b.write('test_data\n') b.write(line) counter += 1 counterFile = open("counter.txt","w") counterFile.write(str(counter)) counterFile.close()