1 ! Copyright (C) 2010 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
3 USING: accessors byte-arrays calendar checksums
4 checksums.internet combinators combinators.smart continuations
5 destructors io.sockets io.sockets.icmp io.timeouts kernel
6 locals pack random sequences system ;
11 TUPLE: echo type identifier sequence data ;
13 : <echo> ( sequence data -- echo )
14 [ 8 16 random-bits ] 2dip echo boa ;
16 : echo>byte-array ( echo -- byte-array )
19 [ type>> 0 0 ] ! code checksum
22 ] output>array "CCSSS" pack-be
23 ] [ data>> ] bi append [
24 internet checksum-bytes 2 4
25 ] keep replace-slice ;
27 : byte-array>echo ( byte-array -- echo )
28 dup internet checksum-bytes B{ 0 0 } assert=
30 "CCSSS" unpack-be { 0 3 4 } swap nths first3
33 : send-ping ( addr raw -- )
34 [ 0 { } <echo> echo>byte-array ] 2dip send ;
36 :: recv-ping ( addr raw -- echo )
38 20 tail byte-array>echo
40 drop addr raw recv-ping
45 HOOK: <ping-port> os ( inet -- port )
47 M: object <ping-port> <raw> ;
49 M: macosx <ping-port> <datagram> ;
51 : ping ( host -- reply )
52 <icmp> resolve-host [ icmp4? ] filter random
54 1 seconds over set-timeout
55 [ [ send-ping ] [ recv-ping ] 2bi ] with-disposal ;
57 : local-ping ( -- reply )
60 : alive? ( host -- ? )
61 [ ping drop t ] [ 2drop f ] recover ;