chickadee » socket » socket-connect

socket-connect so saddrprocedure
socket-connect/ai aisprocedure

socket-connect connects to the remote socket address saddr over the socket so. Upon completion, so will be connected; on connection failure an error is thrown. The return value is unspecified. This is a non-blocking operation; other SRFI-18 threads can continue to run.

If connection fails due to refusal, network down, unreachable host or system enforced timeout, it raises a "transient" error of type (exn i/o net transient), signalling the connection can be retried later if desired. A connection may also raise an (exn i/o net timeout) error after (socket-connect-timeout) milliseconds. If a fatal error occurs, it raises an error of type (exn i/o net), like all other socket procedures.

socket-connect/ai connects to the addresses in the addrinfo list ais sequentially until the connection succeeds or there are no more addresses. If a fatal error occurs while connecting, it aborts immediately; but transient or timeout errors cause it to try the next address. If all attempts fail, the error raised is that of the last attempt. On success, the return value is a fresh connected socket of the appropriate family and type.


 ;; Connect to localhost:22 over IPv4.
 (define so (socket af/inet sock/stream))
 (socket-connect so (inet-address "" 22))
 ;; Connect to localhost:22 over IPv6.
 (define so (socket af/inet6 sock/stream))
 (socket-connect so (inet-address "::1" 22))
 ;; Connect to localhost:22 over IPv4 and return the connected socket.
   (address-information "localhost" 22 family: af/inet))
 ; => #<socket fd:8 af/inet sock/stream>
 ;; Try to connect to localhost:ssh via any address family.  
 ;; In this case, address-information may return the IPv6 loopback
 ;; address "::1" and perhaps "fe80::1", along with the usual 
 ;; IPv4 "".  socket-connect/ai will try them all in order
 ;; and return a new connected socket.  For illustrative purposes
 ;; we use socket-peer-name to show where we connected.

  (socket-connect/ai (address-information "localhost" "ssh")))
 ; => #<sockaddr "[::1]:22">         ;; If ssh listening on ::1
 ; => #<sockaddr "[fe80::1%lo0]:22"> ;; If listening on link-local loopback
 ; => #<sockaddr "">     ;; If listening on only
 ; => error: connection refused      ;; If ssh isn't running