Establishing Outgoing Connections
Performing Active Opens
Now that we know how to set up 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 address 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 double duties. For incoming connections, they define (if required by sock.inconmode) who will be able to connect to the socket. For outgoing connections, this pair defines the IP address and host to which the socket will attempt to connect.
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 Address Resolution Protocol (ARP).
- Attempt to engage the target in a standard TCP connection sequence (SYN-SYN-ACK).
- The connection will either be 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 bells 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 a "UDP" socket to connect, the latter will just resolve the IP address of the target and consider the "connection" established.
Don't 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 explains how to find out the actual connection status at any time (see sock.state and sock.statesimple read-only properties).
The asynchronous nature of the sock. object has some interesting implications. The More On the Socket's Asynchronous Nature topic contains important information on the subject, so make sure you read it!