Client-side connect()
What you'll learn: How to establish a formal handshake between your client program and a remote server using the connect() system call.
The Handshake
In our previous lessons, we created a socket (the phone) and specified an address (the phone number). However, simply having a phone and a number doesn't mean a conversation is happening. To actually talk to a server, your client must initiate a connection.
Think of connect() as the act of dialing the number and waiting for the other party to pick up. In the networking world, this initiates the "TCP Three-Way Handshake." It’s a polite exchange where your computer says "Hello," the server says "Hello back, ready?", and your computer says "Great, let’s talk." Once connect() returns successfully, the virtual circuit is open.
Using the connect() Function
The connect() function requires three pieces of information: the socket file descriptor you created, the address structure containing the server's IP and port, and the size of that address structure.
Here is what the implementation looks like in C:
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
int main() {
int sock_fd;
struct sockaddr_in server_addr;
// 1. Create the socket
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
// 2. Setup the server address (Connecting to localhost on port 8080)
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
// 3. The connect call
// Returns 0 on success, or -1 if the server is unreachable/refused
if (connect(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
printf("Connection failed! Is the server running?\n");
return 1;
}
printf("Connected successfully!\n");
return 0;
}
Why it might fail
Unlike creating a socket, connect() is very likely to fail during real-world use. If the server is offline, if a firewall is blocking the port, or if you typed the wrong IP address, connect() will return -1.
One important detail: for client applications, you usually don't need to call bind(). When you call connect(), the operating system automatically picks an available local port for you and "binds" it behind the scenes. This simplifies your code significantly; you just point at the destination and let the OS handle the local logistics.
Key takeaway
The connect() function transitions a socket from a disconnected state to an active session by performing a handshake with a listening server.