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)
相关推荐
阿里云大数据AI技术6 小时前
阿里云 EMR AI 助手正式发布:从问答工具到全栈智能运维助手
运维·人工智能
orion571 天前
Missing Semester Class1:course overview and introduction of shell
linux
SkyWalking中文站1 天前
认识 Horizon UI · 6/17:Trace 探索器
运维·监控·自动化运维
用户120487221611 天前
Linux驱动编译与加载
linux·嵌入式
火车叼位1 天前
写给初级开发者:SSL、SSH、HTTPS 与证书体系全解析
运维
用户805533698031 天前
Input 子系统架构:Core、Handler、Driver 三层是怎么协作的
linux·嵌入式
用户805533698031 天前
RK-Forge外设系列开篇 - 把板子从「能启动」变成「能用」:Ethernet/SPI/MMC 三个纯接线外设
linux·github·嵌入式
小猿姐2 天前
唯品会大规模数据库云原生实践:基于 KubeBlocks 管理数千实例的统一运维之路
运维·elasticsearch·云原生
七歌杜金房2 天前
我终于又有了自己的 Linux 电脑
linux·debian·mac
SkyWalking中文站2 天前
认识 Horizon UI · 5/17:3D 基础设施地图
运维·监控·自动化运维