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.

If you enjoyed this blog post, you might enjoy my travel book for people interested in science and technology: The Geek Atlas. Signed copies of The Geek Atlas are available.


<$BlogCommentDateTime$> <$BlogCommentDeleteIcon$>

Post a Comment

Links to this post:

<$BlogBacklinkControl$> <$BlogBacklinkTitle$> <$BlogBacklinkDeleteIcon$>
Create a Link

<< Home