|Don't ask to ask, just ask|
Using inetd to serve a socket
It is often the case that one needs to test a system before the hardware is available or on-line. In my case, I'm developing an interface which will talk to a socket on a complex piece of Fab Metrology gear called an Applied Materials NanoSEM, using a complex protocol called SEMI SECS-II/GEM HSMS. I needed a quick and dirty handler to act as the NanoSEM while I get the protocol parser working.
UNIX-like systems such as FreeBSD and Linux have a nifty feature called inetd, which comes to our rescue. inetd runs a program you specify whenever somebody else tries to connect to the socket you've chosen. By making a few simple configuration improvements, we can send our input to the specified socket, and inetd invokes our program, passing our input to it as STDIN. Our handler then processes it and spits out its response as STDOUT back to our socket. Cool, huh? What's even more cool is that if another process (or system) also tries to connect to the same socket, inetd will invoke another copy of our handler without bothering the first one.
Interested? Okay, here's the code...
The server handler:
This little program will process anything that comes in on the specified port, clearing carriage returns and line feeds, and (in this simple case) spitting it back with two spaces in front and a newline at the end. An input containing "endit" causes the handler to exit, and, thanks to the flush sequence at the top, output is immediate. Make your program executable:
Okay, now, here's the setup. In /etc (you need to be superuser), edit /etc/services to add your port number to the known services list, making up a unique name for the service. My port is 6100, its service is 'secshsms', and I've asked it to handle both stream (tcp) and datagram (udp) packets, although this example will only deal with tcp.
Next, edit /etc/inetd.conf to attach your program to that service:
Okay, find inetd and restart it.
From now on, any process that attempts to talk to my machine's port 6100 gets its output routed to my handler sinet.pl.
With that in hand, here's a sample client, adapted from Perl Cookbook recipe 17.10. It can be installed on any machine within a routable network (i.e., no firewall) and it will talk to my handler.
A simple client:
Working from this skeleton, a more elaborate language can be developed. The program on each end can be made to parse and respond to commands from the other.
UPDATE 1: changed server user to nobody, thank you idsfa.
"There's more than one level to any answer."