Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ TCP Echo Server | Building Network Applications
C Networking Basics

bookTCP Echo Server

メニューを表示するにはスワイプしてください

Note
Definition

A TCP echo server is a simple network program that accepts TCP connections from clients and sends back exactly the same data it receives. This behavior is called echoing.

In a TCP echo setup, the server waits for incoming client connections. When a client connects and sends a message, the server immediately sends that message back to the client. The client then reads and displays the echoed response. This example is widely used to learn socket programming because it demonstrates all core steps of TCP communication: creating sockets, binding to an address, listening for connections, accepting clients, receiving data, and sending responses.

echo_server.c

echo_server.c

echo_client.c

echo_client.c

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #define PORT 12345 #define BUFFER_SIZE 1024 int main() { int server_fd, client_fd; struct sockaddr_in server_addr, client_addr; socklen_t addr_len = sizeof(client_addr); char buffer[BUFFER_SIZE]; ssize_t bytes_read; // Create a TCP socket server_fd = socket(AF_INET, SOCK_STREAM, 0); if (server_fd < 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Set up the server address struct server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; // Listen on any interface server_addr.sin_port = htons(PORT); // Bind the socket to the specified port and address if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { perror("bind failed"); close(server_fd); exit(EXIT_FAILURE); } // Listen for incoming connections if (listen(server_fd, 1) < 0) { perror("listen failed"); close(server_fd); exit(EXIT_FAILURE); } printf("Echo server listening on port %d...\n", PORT); // Accept a client connection client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addr_len); if (client_fd < 0) { perror("accept failed"); close(server_fd); exit(EXIT_FAILURE); } printf("Client connected.\n"); // Echo loop: receive data and send it back while ((bytes_read = recv(client_fd, buffer, BUFFER_SIZE, 0)) > 0) { // Send the received data back to the client send(client_fd, buffer, bytes_read, 0); } printf("Client disconnected.\n"); close(client_fd); close(server_fd); return 0; }
question mark

What is the main function of an echo server in networking?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 2.  1
some-alt