Paste: udp-client

Author: mrjbq7
Mode: factor
Date: Tue, 27 Apr 2010 14:42:12
Plain Text |
! Copyright (C) 2010 John Benediktsson
! See http://factorcode.org/license.txt for BSD license

USING: alien.c-types bit-arrays byte-arrays classes.struct
destructors io.sockets.private io.sockets.unix unix.ffi
unix.time ;

IN: udp

: <udp> ( -- fd )
    [ AF_INET SOCK_DGRAM socket-fd fd>> ] with-destructors ;

: udp-send ( fd byte-array addr -- )
    [ dup length 0 ] dip make-sockaddr/size
    sendto 0 < [ "send error" throw ] when ;

: udp-recv ( fd n -- byte-array )
    <byte-array> [ dup length 0 recv ] keep swap head ;

! Factor's bit-arrays are an array of bytes, OS X expects
! FD_SET to be an array of cells, so we have to account for
! byte order differences on big endian platforms
: munge ( i -- i' )
    little-endian? [ BIN: 11000 bitxor ] unless ; inline

: create-fdset ( fd -- fdset )
    [ t ] dip munge FD_SETSIZE 8 * <bit-array>
    [ set-nth ] keep ;

: wait-for-read ( fd -- )
    [ 1 + ] [ create-fdset ] bi f f
    timeval <struct> 1 >>sec
    select 0 < [ "select error" throw ] when ;

Annotation: ntp

Author: mrjbq7
Mode: factor
Date: Tue, 27 Apr 2010 14:44:20
Plain Text |
: ntp-send ( fd -- )
    B{ HEX: 1b 0 0 0 0 0 0 0
       0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
       0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
       0 0 0 0 0 0 0 0 }
    "209.114.111.1" 123 <inet4> udp-send ;

CONSTANT: TIME1970 2208988800

: >millis ( integ frac -- millis )
    [ TIME1970 - ] [ 32 2^ / ] bi* + 1000 * ;

TUPLE: data leap version mode stratum poll precision
root-delay root-dispersion ref-id ref-timestamp
orig-timestamp recv-timestamp tx-timestamp ;

: ntp-recv ( fd -- ntp )
    [ wait-for-read ] [ 128 udp-recv ] bi ;

Annotation: using it

Author: mrjbq7
Mode: factor
Date: Tue, 27 Apr 2010 14:45:07
Plain Text |
: ntp ( -- data )
    <udp> [ ntp-send ] [ ntp-recv ] bi ;

New Annotation

Summary:
Author:
Mode:
Body: