Syslog example (passively receive UDP packets)

Previous topic - Next topic

Moru

I needed a simple syslog for work so I figured I would look into what is needed. Turns out it's realy simple, less than 5 min and I have something simple running :-)

This code will wait for messages on port 514 (or whatever you specify) and log them all to a file and print on screen. The program should be made as console application for output too work but can be made as a normal program too, if you rewrite the text putput.

Code (glbasic) Select
// --------------------------------- //
// Project: Syslog
// Start: Monday, July 26, 2010
// IDE Version: 8.036


GLOBAL sock%               // The socket connection
GLOBAL port% = 514        // Port number to use

LOCAL ok%, ip%, rv%, msg$

log("Receiving on UDP-port " + port)

ok = SOCK_INIT()    // Init network
IF ok
    sock = SOCK_UDPOPEN(port)    // Get the socket so we can recieve on the port
    IF sock <> -1
        WHILE rv <> -1
            rv = SOCK_RECV(sock, msg$, 1024)
            IF rv>0 THEN log("message recieved: ["+msg$+"]")
            IF rv=-1
                log(NETGETLASTERROR$())     // Didn't work, tell user why
                SOCK_CLOSE(sock)
            ENDIF
            SLEEP 10
        WEND
    ELSE
        log(NETGETLASTERROR$())
    ENDIF
ELSE
    log(NETGETLASTERROR$())
ENDIF
KEYWAIT



FUNCTION log: str$
LOCAL ok%, id%

    STDOUT "\n"+str$
    id = GENFILE()
    ok = OPENFILE(id, "syslog.log", -1)
    IF ok
    WRITELINE id, "\n"+str$
    CLOSEFILE id
ENDIF
ENDFUNCTION