socket编程入门实践——基于TCP的echo服务器/客户端

本文介绍了学习Linux网络编程过程中的一个实践项目——基于TCP协议的echo服务器和客户端。通过详细注释的代码展示了如何创建并运行这两个程序,强调了理解和掌握TCP服务器及客户端基本函数调用的重要性。
摘要由CSDN通过智能技术生成

最近在学习Linux网络编程,参考《TCP/IP网络编程》写下这个socket编程示例——基于TCP的echo服务器/客户端。echo服务器,顾名思义就是将收到的客户端数据原封不动地传回客户端。
无论多么复杂的TCP服务器,其函数调用顺序几乎都是socket -> bind -> listen -> accept -> read/write -> close,因此掌握这些基本函数的使用方法是很重要的。以下是基于TCP的echo服务器的完整代码(附带详细注释):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUF_SIZE 1024

// to handle errors
void errorHandling(char* message) {
   
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
   
    // sockets of the server and the client
    int serv_sock, clnt_sock;
    // buffer zone
    char message[BUF_SIZE];
    // the length of the message received
    int str_len;

    // the ip addresses of the server and the client
    struct sockaddr_in serv_adr, clnt_adr;
    // the size of the client address
    socklen_t clnt_adr_sz;

    // check if the number of arguments is correct
    if (argc != 3) {
   
        printf("Usage: %s <IP Address> <Port>\n", argv[0]);
        exit(1);
    }

    // get a server socket
    serv_sock = socket(PF_INET, SOCK_STREAM, 0);    // domain, service types (should be SOCK_STREAM because of TCP), detailed protocol(usually 0)
    // if failed
    if (serv_sock == -1) 
  • 11
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值