Establishing Outgoing Connections

Performing active opens

Now that we know how to setup the sockets to accept incoming TCP connections and UDP "connections" we move on to learning about establishing connections of our own, or, as is often said, performing "active opens".

Establishing an outgoing connection is always an explicit action- you use the sock.connect method to attempt to do this. Once you do this the socket will try to perform an active open to the IP and port specified by the sock.targetip and sock.targetport properties. There is also a sock.targetinterface property — this one defines which network interface the new connection will be passing through.


As you can see, the sock.targetip and sock.targetport properties perform a double-duty: for incoming connections they define (if required by the sock.inconmode) who will be able to connect to the socket. For outgoing connections this pair defines IP and host to which the socket will attempt to connect.

Notice, that your sock.connect invocation will only work if you do this while the socket is in the "closed" state (see Checking Connection Status).

Active opens for TCP

Once you tell a "TCP" socket to connect, the socket will do the following:

  • Resolve the IP address of the target using the ARP protocol.
  • Attempt to engage the target in a standard TCP connection sequence (SYN-SYN-ACK).
  • Connection will be either established, or this will fail. Your program has a way to monitor this- see Checking Connection Status.


If what we've just said doesn't ring any bell for you, don't worry. These, indeed, are very technical things and you don't have to understand them fully to be able to use the sock object.

"Active opens" for UDP

When you tell an "UDP" socket to connect, the latter will just resolve the IP address of the target and consider "connection" established.

Do not forget: connection handling is fully asynchronous!

Keep in mind that the sock object handles communications asynchronously. When the VM executes the sock.connect method it does not mean that the connection is established by the time the VM gets to the next program statement. Executing sock.connect merely instructs the master process to start establishing the connection. Connection establishment can take some time and your application doesn't have to wait for that to complete. Checking Connection Status topic explains how to find out actual connection status at any time (see sock.state and sock.statesimple R/O properties).


Asynchronous nature of the sock object has some interesting implications. More On the Socket's Asynchronous Nature topic contains important information on the subject, so make sure you read it!