[Haskell-cafe] UDP client/server

Gregory Wright gwright at comcast.net
Thu Jan 11 10:35:49 EST 2007

Hi John,

On Jan 11, 2007, at 1:58 AM, John Ky wrote:

> Hello,
> Does anyone know where I can find a simple UDP client/server  
> written in Haskell?
> Something along the lines of an echo server would do.
> Thanks
> -John


-- UDPEchoServer.hs: Exactly what the name says, a datagram echo server.

module Main (main) where

import Network.Socket
import System.Posix.Directory
import System.Posix.Files
import System.Posix.IO
import System.Posix.Process
import System.Exit

echoPort = 9900
maxline = 1500

-- The daemon infrastructure

main :: IO ()
main = do
           pid <- forkProcess child
           exitImmediately ExitSuccess

child :: IO ()
child = do
           -- Set up the working directory, mask and standard i/o
           -- for a daemon process (these will be inherited by
           -- the forked process):

           changeWorkingDirectory "/"
           setFileCreationMask 0

           mapM_ closeFd [stdInput, stdOutput, stdError]
           nullFd <- openFd "/dev/null" ReadWrite Nothing  
           mapM_ (dupTo nullFd) [stdInput, stdOutput, stdError]

           closeFd nullFd

           createSession     -- This child becomes a process and session
                             -- group leader. This prevents the child of
                             -- this process (the daemon) from
                             -- ever getting a controlling terminal.
           pid' <- forkProcess echoserver

           exitImmediately ExitSuccess

-- The echo server daemon

echoserver :: IO ()
echoserver = do
           withSocketsDo $ do
                   sock <- socket AF_INET Datagram 0
                   bindSocket sock (SockAddrInet echoPort iNADDR_ANY)
                   socketEcho sock

socketEcho :: Socket -> IO ()
socketEcho sock = do
           (mesg, recv_count, client) <- recvFrom sock maxline
           send_count <- sendTo sock mesg client
           socketEcho sock


On my OS X/ppc 10.4.8 system, the above builds with ghc 6.6 and if I  
open one
terminal with

gregory-wrights-powerbook-g4-17> nc -u 9900

and another with

gregory-wrights-powerbook-g4-17> nc -ul -p 9900

whatever I type into the first terminal appears on the second.  You  
may have to
consult your documentation for the options to your version of nc (or  
if you use that instead).

I was also able to see that the server returned packets using hping3.

Needless to say, the above is just an example, and is by no means  
I think I adapted it from something I found on the old wiki and  
updated it
to work with the current libraries.

Best Wishes,


More information about the Haskell-Cafe mailing list