Time for a new programming challenge! This one should be easier than the last one, and can probably be done in a lot more languages: listen on a socket for messages coming over the network, then print out the messages to a log file.
The rules for this challenge are as follows:
That sends the message 'hello there!' to port 6789 at the address 127.0.0.1. You can replace that IP address and port number with whatever you're using.
I'll get the challenge started with an example in Tcl:
Here's a message I sent from another machine (192.168.1.3) to my machine (192.168.1.100) where the program is listening on port 6789:
Here's what the log file looks like:
The rules for this challenge are as follows:
- Open a TCP socket on some open port (say, port 6789).
- When messages are received on that port, print to a log file /tmp/socket.log the following information:
1. the date and time that the message was received
2. the IP address that the message came from
3. the message itself - The above information should be appended to the log file in the following format:
Code:<YYYY-MM-DD> <hh:mm:ss AM|PM> from <address>: <message>
Code:2013-04-25 02:53:58 PM from 127.0.0.1: hello there!
- Post your code (and any special compilation instructions, if necessary).
Code:
echo 'hello there!' > /dev/tcp/127.0.0.1/6789
I'll get the challenge started with an example in Tcl:
Code:
#!/usr/bin/tclsh
set log [open "/tmp/socket.log" a+]
set sock [socket -server accept 6789]
fconfigure ${sock} -blocking 0 -encoding utf-8 -buffering line
proc accept {s addr p} {
fileevent $s readable[list process $s ${addr}]
}
proc process {s addr} {
global forever log
set message [gets $s]
if {[eof $s]} {
close $s
set forever done
} else {
puts ${log} "[clock format [clock seconds] -format "%Y-%m-%d %I:%M:%S %p"]\
from ${addr}: ${message}"
flush ${log}
}
}
while {1} {vwait forever}
Code:
$ echo 'hello there!' > /dev/tcp/192.168.1.100/6789
Code:
$ tail -f /tmp/socket.log
2013-04-25 02:53:58 PM from 192.168.1.3: hello there!
2013-04-25 03:23:46 PM from 192.168.1.3: hello again!