C++
TCP client
Learn to write a TCP client.
What is a TCP client?
A TCP client is the side that connects to a server. It first creates a socket, then prepares the server address and connects with connect(). Once connected it exchanges data with send and recv.
The server address is prepared with the sockaddr_in struct: addr.sin_family = AF_INET; addr.sin_port = htons(8080); addr.sin_addr.s_addr = inet_addr("127.0.0.1");. Here htons converts the port number to network byte order. inet_addr converts an IP string to a numeric address. Then connect(sock, (sockaddr*)&addr, sizeof(addr)) establishes the connection.
Preparing the address struct
The sockaddr_in struct defines an IPv4 address. You fill three main fields: sin_family (AF_INET), sin_port (with htons), sin_addr.s_addr (with inet_addr). The prepared address is passed to connect or bind.
Example: sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(8080); addr.sin_addr.s_addr = inet_addr("127.0.0.1");. 127.0.0.1 means the local machine (localhost). In the connect call the address is cast to a generic socket address with (sockaddr*)&addr. This cast is the standard way the POSIX API unifies address types.
Exercise Set up a TCP client connection
Add #include <sys/socket.h>, #include <netinet/in.h> and #include <arpa/inet.h>. Create a socket with int sock = socket(AF_INET, SOCK_STREAM, 0);. Define sockaddr_in addr; and set addr.sin_family = AF_INET;, addr.sin_port = htons(8080);, addr.sin_addr.s_addr = inet_addr("127.0.0.1");. Call connect(sock, (sockaddr*)&addr, sizeof(addr));. Print std::cout << "Connected";.
Show example solution
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
connect(sock, (sockaddr*)&addr, sizeof(addr));
std::cout << "Connected";
return 0;
}
Test yourself
-
Match each piece to its role
- sockaddr_in
- Address struct
- htons(8080)
- Port to network order
- inet_addr("127.0.0.1")
- IP string to address
- connect(sock, ...)
- Establishes connection
-
What does htons do?
- Sends data
- Converts a port to network byte order
- Closes a socket
- Converts an IP address
Show answer
Converts a port to network byte order — htons converts a port number to network byte order.
-
Complete the connect call
____(sock, (sockaddr*)&addr, sizeof(addr));
Show answer
connect(sock, (sockaddr*)&addr, sizeof(addr));
Next lesson: TCP server