netcat 与 UDP 的奇怪行为 [英] Strange behaviour of netcat with UDP

查看:23
本文介绍了netcat 与 UDP 的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到使用 netcat 和 UDP 时出现了一种奇怪的行为.我启动了一个侦听 UDP 端口的 netcat 实例(实例 1):

I noticed a strange behaviour working with netcat and UDP. I start an instance (instance 1) of netcat that listens on a UDP port:

nc -lu -p 10000

所以我启动了另一个 netcat 实例(实例 2)并尝试将数据报发送到我的进程:

So i launch another instance of netcat (instance 2) and try to send datagrams to my process:

nc -u 127.0.0.1 10000

我看到了数据报.但是如果我关闭实例 2 并重新启动 netcat(实例 3):

I see the datagrams. But if i close instance 2 and relaunch again netcat (instance 3):

nc -u 127.0.0.1 10000

我在实例 1 的终端上看不到数据报.显然,操作系统在实例 3 相对于实例 2 分配了不同的 UDP 源端口,问题是:如果我使用相同的实例 2 源端口(例如 50000):

i can't see datagrams on instance 1's terminal. Obsiously the operating system assigns a different UDP source port at the instance 3 respect to instance 2 and the problem is there: if i use the same instance'2 source port (example 50000):

 nc -u -p 50000 127.0.0.1 10000

netcat 的实例 1 再次接收数据报.UDP 是一种无连接协议,为什么?这是标准的 netcat 行为吗?

again the instance 1 of netcat receives the datagrams. UDP is a connection less protocol so, why? Is this a standard netcat behaviour?

推荐答案

nc 正在侦听 UDP 套接字时,它锁定"到它的第一个数据包的源端口和源 IP收到.查看此跟踪:

When nc is listening to a UDP socket, it 'locks on' to the source port and source IP of the first packet it receives. Check out this trace:

socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP) = 3
setsockopt(3, SOL_SOCKET, SO_REUSEADDR, [1], 4) = 0
bind(3, {sa_family=AF_INET, sin_port=htons(10000), sin_addr=inet_addr("127.0.0.1")}, 16) = 0
recvfrom(3, "f
", 2048, MSG_PEEK, {sa_family=AF_INET, sin_port=htons(52832), sin_addr=inet_addr("127.0.0.1")}, [16]) = 2
connect(3, {sa_family=AF_INET, sin_port=htons(52832), sin_addr=inet_addr("127.0.0.1")}, 16) = 0

在这里你可以看到它创建了一个UDP套接字,将其设置为地址重用,并将其绑定到端口10,000.一旦它收到第一个数据报(来自端口 52,832),它就会发出一个 connect 系统调用,将它连接"到 127.0.0.1:52,832.对于 UDP,connect 拒绝所有与 connect 中的 IP 和端口不匹配的数据包.

Here you can see that it created a UDP socket, set it for address reuse, and bound it to port 10,000. As soon as it received its first datagram (from port 52,832), it issued a connect system call 'connecting' it to the 127.0.0.1:52,832. For UDP, a connect rejects all packets that don't match the IP and port in the connect.

这篇关于netcat 与 UDP 的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆