'
' This documentational program shows how to catch all issues in network connections.
'
' May 2010, PvE - GPL.
'---------------------------------------------------------------------------------------------
'
' We set our own error routine in case the remote site is not reachable.
TRAP LOCAL
CATCH GOTO network_error

' This function will be executed if the DNS lookup takes too long. Put in other actions to
'   followup on this erroneous situation. For now we lazily end.
SUB dns_interrupt
    PRINT "That DNS lookup took too long! Exiting..."
    END
END SUB

' The site we want to reach. Try some variations.
' Try site$ = "11.22.33.44" - socket problem
' Try site$ = "www.google.123.com" - DNS problem
' Try site$ = "www.google.com" - success
site$ = "www.google.com"
port$ = "80"

' We set socket creation to a maximum of 1 second. So if the remote site is unavailable, the
'   socket cannot be created and a network error will occur, jumping to the LABEL below.
OPTION SOCKET 1

' DNS lookups may not take longer than 2 seconds. ALARM will break through any action, therefore
'   we set it just before the OPEN NETWORK statement.
ALARM dns_interrupt, 2000

' Now try to reach the site.
' (1) If this statement fails, the program jumps to the LABEL below.
' (2) If this statement takes too long, there is a DNS problem and it will be interrupted by ALARM.
OPEN CONCAT$(site$, ":", port$) FOR NETWORK AS mynet
CLOSE NETWORK mynet

' After successful socket creation we must cancel the ALARM, otherwise it will execute anyway.
ALARM dns_interrupt, 0

PRINT "Site '", site$, "' is reachable."
END

' Show network error. If needed use RESUME to create a RETRY mechanism.
LABEL network_error
    PRINT "Site not reachable! ", ERR$(ERROR)