Linux系统编程——TCP客户端

Linux系统编程------TCP客户端

客户端流程

  1. 创建流式套接字,通过socket创建
  2. 填充服务器的网络信息结构体 ------ struct sockaddr_in
  3. 与服务器建立连接,通过connect实现
  4. 收发数据------recv/send
  5. 关闭套接字------close

connect函数

c 复制代码
int connect(int sockfd, const struct sockaddr*, socklen_t addrlen);

所需头文件:sys/socket.h

sockfd:客户端的sock套接字

addr:目标服务器的地址结构体

addrlen:地址结构体的长度

返回值:成功返回0,失败返回-1并重置错误码。

实例:TCP客户端

代码:

c 复制代码
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdbool.h>

int main(int argc, char** argv) {
    //创建流式套接字
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
        if (sock_fd == -1) {
            perror("创建socket失败");
                return -1;
        }

        //配置服务器地址信息
    struct sockaddr_in server_info = {0};

        //IPV协议簇
        server_info.sin_family = AF_INET;

        //端口号
    server_info.sin_port = htons(8888);

        //ip地址
    server_info.sin_addr.s_addr = inet_addr("192.168.203.141");

        //连接服务器
        int ret = connect(sock_fd, (const struct sockaddr*)&server_info, sizeof(server_info));

    if (ret == -1 ) {
           perror("连接失败");
           return -1;
        }

    char buf[128] = {0};
        while(true) {
            memset(buf, 0, sizeof(buf));
                //从键盘中读取输入
            fgets(buf, sizeof(buf), stdin);
                int nbytes = send(sock_fd, buf, sizeof(buf), 0);

                if (nbytes == -1 ) {
                   perror("发送失败");
                   return -1;
                }

                //接收数据
            memset(buf, 0, sizeof(buf));
                int nbytes_recv = recv(sock_fd, buf, sizeof(buf), 0);

                if (nbytes_recv == -1) {
                   perror("读取失败");
                   return -1;
                } else if(nbytes_recv == 0) {
                   printf("服务端关闭连接,退出程序\n");
                   return 0;
                }

                printf("服务器发来的数据:%s\n",buf);
        }

    return 0;
}

```
运行结果:
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/1b6fd9616203489d8754993468d946cd.png)
相关推荐
未济2 天前
linux 配置环境变量
linux
傲世仙尊2 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
_艾伦 耶格尔.2 天前
进程间通信
linux
AI职业加油站2 天前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
Liuqy-052 天前
Linux IO编程——静态库、动态库
linux
此冬歌咏2 天前
K8s 节点故障实战:优雅驱逐 31 秒,硬故障 331 秒,以及那个永远 Pending 的 Pod
运维·k8s
彧azz2 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
-梅2 天前
linux(8) 软硬链接
linux·运维·服务器
AIgorithmGEEK2 天前
[Linux]线程三部曲(上):一个执行流的诞生——从操作系统一路拆到 pthread_create
linux·线程·pid