Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour of netcat with UDP

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 

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

nc -u 127.0.0.1 10000 

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

nc -u 127.0.0.1 10000 

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 

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

like image 237
MirkoBanchi Avatar asked Oct 08 '11 12:10

MirkoBanchi


People also ask

Does Netcat use UDP?

How To Communicate through Netcat. Netcat is not restricted to sending TCP and UDP packets. It also can listen on a port for connections and packets.


2 Answers

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 

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.

like image 173
David Schwartz Avatar answered Sep 29 '22 13:09

David Schwartz


Use the -k option:

nc -l -u -k 0.0.0.0 10000 
  • -k means keep-alive, that netcat keeps listening after each connection
  • -u means UDP
  • -l listening on port 10000
like image 27
Nasser Al-Wohaibi Avatar answered Sep 29 '22 12:09

Nasser Al-Wohaibi