netcat与UDP的奇怪行为 [英] Strange behaviour of netcat with 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源端口,问题就出在这里:如果我使用相同的instance'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\n", 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屋!