Quantcast
Channel: FedoraForum.org
Viewing all articles
Browse latest Browse all 36158

Programming challenge: Listen on a socket

$
0
0
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:
  1. Open a TCP socket on some open port (say, port 6789).
  2. 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
  3. 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>
    For example, if the message "hello there!" was sent from IP address 127.0.0.1 at 2:53:58 PM on April 25, 2013, then you would append this to the log file:
    Code:

    2013-04-25 02:53:58 PM from 127.0.0.1: hello there!
  4. Post your code (and any special compilation instructions, if necessary).
You don't have to worry about writing a network client to test your code, since in Linux you can just use bash to send messages to a port:
Code:

echo 'hello there!' > /dev/tcp/127.0.0.1/6789
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:
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}

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:
Code:

$ echo 'hello there!' > /dev/tcp/192.168.1.100/6789
Here's what the log file looks like:
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!


Viewing all articles
Browse latest Browse all 36158

Trending Articles