TCP client
- C++ course
- Advanced
- Lesson 56/83
- 5 min
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.
Practice 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";.
Starter code
#include <iostream>
// Add socket headers, prepare socket and address
int main() {
// Add socket, addr and connect calls
return 0;
}Sample 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;
}Expected output
Connected
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
sockaddr_in |
Address struct |
htons(8080) |
Port to network order |
inet_addr("127.0.0.1") |
IP string to address |
connect(sock, ...) |
Establishes connection |
2 What does htons do?
- Sends data
- Converts a port to network byte order Correct answer
- Closes a socket
- Converts an IP address
Explanation: htons converts a port number to network byte order.
3 Complete the connect call
____(sock, (sockaddr*)&addr, sizeof(addr));
connect(sock, (sockaddr*)&addr, sizeof(addr));
Explanation: connect links the client to the server.