Saturday, December 08, 2012

Listen on a UDP port and dump received lines of data

I needed to quickly fake up a syslog server for some debugging and wrote a small Perl program to listen for messages (lines of text) on a UDP port and dump them to the console. The program listens on a port specified on the command-line and simply prints out whatever it receives. It is only suitable for line oriented protocols since it uses the Perl <FN> operator to read data.

Here it is:

# - listen on UDP port and dump out whatever has been received                                  

use strict;
use warnings;
use Socket;

die "Usage: <port>" if (!defined($ARGV[0]));

socket(UDP, PF_INET, SOCK_DGRAM, getprotobyname("udp"));
bind(UDP, sockaddr_in($ARGV[0], INADDR_ANY));
print $_ while (<UDP>);

PS Some people have asked why I'm not using netcat. The answer is that netcat works fine if only one 'connection' is made to the UDP port. With multiple it doesn't work and I want an arbitrary number of UDP sources to throw data at this program successively. For details, see this StackOverflow question.


Eitan said...

Why not use netcat?

nc -l -u [port]
test it with
nc -u localhost [port]

(P.S., you really should /usr/bin/env perl instead of an absolute path)

John Graham-Cumming said...

Because netcat with UDP doesn't work with multiple 'connections':

JonasL said...

Thanks! Added to our pastebin

Unknown said...

How about socat?

socat -u udp-recv:1234 -

socat is my tool of choice for anything involving TTYs and networks. We’ve used it at work to forward data between USB serial devices and a TCP server for several years now.

Unknown said...

Carey's right, use socat(1). Given the variety of differing netcat versions and its more limited abilities, I reach for socat by default.

Also, your "Perl <fh> operator" is rendered without the "<fh>".

John Graham-Cumming said...

socat looks great and works as Carey describes.

Q said...

I was thinking about ncat as part of nmap. However, a quick test shows that ncat has the same issue as plain nc. Ncat has a --broker option but it doesn't work for UDP.

[email protected]:~# ncat --broker -l -u -k -p 80
Ncat: UDP mode does not support connection brokering.
If this feature is important to you, write [email protected] with a
description of how you intend to use it, as an aid to deciding how UDP
connection brokering should work. QUITTING.


Why is not working me the script due a "_while" sentence?

HankB said...

Thanks for the post. I was wrestling with how to receive multiple UDP broadcast packets and didn't find the necessary socat syntax until I found this post. Both and socat meet my needs. :)