How to write a simple TCP client/server in C
The answer is that writing a simple TCP client and server requires the socket programming interface provided by the operating system. The server completes communication by creating sockets, binding addresses, listening to ports, accepting connections, and sending and receiving data. The client realizes interaction by creating sockets, connecting to servers, sending requests, and receiving responses. The sample code shows the basic implementation of using the Berkeley socket API on Linux or macOS, including the necessary header files, port settings, error handling and resource release. After compilation, run the server first and then run the client to achieve two-way communication. The Windows platform needs to initialize the Winsock library. This example is a blocking I/O model, suitable for learning basic socket programming.

Writing a simple TCP client and server in C involves using the socket programming interface provided by the operating system (typically the Berkeley sockets API on Unix-like systems, or Winsock on Windows). Below is a basic example that works on Linux or macOS. For Windows, slight modifications are needed (like initializing Winsock).
Basic TCP Server in C
The server listens on a port, accepts a client connection, receives a message, and sends a response.
// server.cpp
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024] = {0};
const char *hello = "Hello from server";
// Create socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Define server address
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8080);
// Bind the socket
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
close(server_fd);
exit(EXIT_FAILURE);
}
// Listen for incoming connections
if (listen(server_fd, 3) < 0) {
perror("listen");
close(server_fd);
exit(EXIT_FAILURE);
}
std::cout << "Server listening on port 8080...\n";
// Accept a connection
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
close(server_fd);
exit(EXIT_FAILURE);
}
// Read data from client
read(new_socket, buffer, 1024);
std::cout << "Client: " << buffer << std::endl;
// Send response
send(new_socket, hello, strlen(hello), 0);
std::cout << "Hello message sent\n";
// Cleanup
close(new_socket);
close(server_fd);
return 0;
}Basic TCP Client in C
The client connects to the server, sends a message, and reads the response.
// client.cpp
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
const char *hello = "Hello from client";
char buffer[1024] = {0};
// Create socket
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("Socket creation error");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8080);
// Convert IPv4 address from text to binary
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
perror("Invalid address / Address not supported");
close(sock);
return -1;
}
// Connect to server
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
perror("Connection failed");
close(sock);
return -1;
}
// Send message to server
send(sock, hello, strlen(hello), 0);
std::cout << "Hello message sent\n";
// Read response
read(sock, buffer, 1024);
std::cout << "Server: " << buffer << std::endl;
// Cleanup
close(sock);
return 0;
}How to Compile and Run
On Linux/macOS:
g server.cpp -o server g client.cpp -o client # Terminal 1 ./server # Terminal 2 (after server is running) ./client
Expected output:
- Server prints:
Server listening on port 8080..., then the client message, thenHello message sent. - Client prints:
Hello message sent, thenServer: Hello from server.
Key Points
- Headers :
sys/socket.h,netinet/in.h,arpa/inet.h,unistd.hare essential for socket programming on Unix. - Port : The server binds to port 8080. Make sure it's free.
- IP Address : The client uses
127.0.0.1(localhost). Change if connecting to a remote server. - Blocking I/O : These examples use blocking sockets. Real applications may use non-blocking I/O or multiple threads.
- Error Handling : Always check return values of socket functions.
Notes for Windows
On Windows, you must:
- Include
<winsock2.h>and link withws2_32.lib. - Call
WSAStartup()before using sockets. - Call
WSACleanup()at the end.
Example snippet:
WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData); // ... socket code ... WSACleanup();
This is a minimal working example. In production, you'd add error recovery, support for multiple clients (using fork , threads, or async I/O), and better data framing.
Basically just the essentials to get a socket pair talking.
The above is the detailed content of How to write a simple TCP client/server in C. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
How to fix missing MSVCP71.dll in your computer? There are only three methods required
Aug 14, 2025 pm 08:03 PM
The computer prompts "MsVCP71.dll is missing from the computer", which is usually because the system lacks critical running components, which causes the software to not load normally. This article will deeply analyze the functions of the file and the root cause of the error, and provide three efficient solutions to help you quickly restore the program to run. 1. What is MSVCP71.dll? MSVCP71.dll belongs to the core runtime library file of Microsoft VisualC 2003 and belongs to the dynamic link library (DLL) type. It is mainly used to support programs written in C to call standard functions, STL templates and basic data processing modules. Many applications and classic games developed in the early 2000s rely on this file to run. Once the file is missing or corrupted,
C operator overloading example
Aug 15, 2025 am 10:18 AM
Operator overloading in C allows new behaviors of standard operators to be assigned to custom types, 1. Return new objects through member function overloading; 2. Overload = Modify the current object and return reference; 3. Friend function overloading
C vector of strings example
Aug 21, 2025 am 04:02 AM
The basic usage of std::vector includes: 1. Declare vector; 2. Add elements with push_back(); 3. Initialize with initialization list; 4. Loop traversal with range for; 5. Access elements through index or back(); 6. Direct assignment of values to modify elements; 7. Delete the end elements with pop_back(); 8. Call size() to get the number of elements; it is recommended to use constauto& to avoid copying, pre-allocate reserve() to improve performance, and pay attention to checking that it is not empty before access. This data structure is an efficient and preferred way to handle string lists.
C false sharing example
Aug 16, 2025 am 10:42 AM
Falsesharing occurs when multiple threads modify different variables in the same cache line, resulting in cache failure and performance degradation; 1. Use structure fill to make each variable exclusively occupy one cache line; 2. Use alignas or std::hardware_destructive_interference_size for memory alignment; 3. Use thread-local variables to finally merge the results, thereby avoiding pseudo-sharing and improving the performance of multi-threaded programs.
How to write a simple TCP client/server in C
Aug 17, 2025 am 01:50 AM
The answer is that writing a simple TCP client and server requires the socket programming interface provided by the operating system. The server completes communication by creating sockets, binding addresses, listening to ports, accepting connections, and sending and receiving data. The client realizes interaction by creating sockets, connecting to servers, sending requests, and receiving responses. The sample code shows the basic implementation of using the Berkeley socket API on Linux or macOS, including the necessary header files, port settings, error handling and resource release. After compilation, run the server first and then run the client to achieve two-way communication. The Windows platform needs to initialize the Winsock library. This example is a blocking I/O model, suitable for learning basic socket programming.
How to write a basic Makefile for a C project?
Aug 15, 2025 am 11:17 AM
AbasicMakefileautomatesC compilationbydefiningruleswithtargets,dependencies,andcommands.2.KeycomponentsincludevariableslikeCXX,CXXFLAGS,TARGET,SRCS,andOBJStosimplifyconfiguration.3.Apatternrule(%.o:%.cpp)compilessourcefilesintoobjectfilesusing$
How to link libraries in C
Aug 21, 2025 am 08:33 AM
To link libraries in C, you need to use -L to specify the library path when compiling, -l to specify the library name, and use -I to include the header file path to ensure that the static or dynamic library files exist and are named correctly. If necessary, embed the runtime library path through -Wl,-rpath, so that the compiler can find the declaration, the linker can find the implementation, and the program can be successfully built and run.
How to configure IntelliSense for C in VSCode
Aug 16, 2025 am 09:46 AM
To correctly configure IntelliSense for C in VSCode, first install Microsoft's C/C extension, then set the compiler path, include directories and C standards. You can manually configure the build information by editing c_cpp_properties.json or automatically obtain the build information using compile_commands.json. Finally, restart and verify that the IntelliSense function is working properly, ensuring that code completion, syntax highlighting and error detection are accurate.


