c语言实现简单的tcp客户端

功能:实现一个简单的tcp客户端,连接本地端口8888的tcp服务端,并发送一条报文。

cpp 复制代码
/* 
 * File:   main.c
 * Author: vincent
 *
 * Created on 2023年8月3日, 上午9:56
 */

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

#define TARGET_PORT 8888
#define TARGET_IP "127.0.0.1"

/*
 * 
 */
int main(int argc, char** argv)
{
    int ret = 1;
    int i;
    unsigned char recv_buff[1024] = {0};
    int read_len = 0;
    int send_len = 0;
    unsigned char *send_data = "hello,this is a tcp client\n";

    //创建套接字
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd < 0)
    {
        printf("socket err\n");
        return -1;
    }
    printf("socket create success sfd=%d\n", socket_fd);

    struct sockaddr_in dest;
    socklen_t len = sizeof (dest);
    dest.sin_family = AF_INET;
    dest.sin_port = htons(TARGET_PORT);
    dest.sin_addr.s_addr = inet_addr(TARGET_IP);
    ret = connect(socket_fd, (const struct sockaddr *) &dest, len);
    if (ret < 0)
    {
        perror("connect");
        close(socket_fd);
        socket_fd = -1;
        return -1;
    }


    send_len = send(socket_fd, send_data, strlen(send_data), 0);
    if (send_len <= 0)
    {
        printf("send err\n");
        close(socket_fd);
        socket_fd = -1;
        return -1;
    }

    memset(recv_buff, 0x00, sizeof (recv_buff));

    read_len = recv(socket_fd, recv_buff, sizeof (recv_buff), 0);
    if (read_len < 0)
    {
        printf("recv err\n");
        close(socket_fd);
        socket_fd = -1;
        return -1;
    } else if (read_len == 0)
    {
        printf("close \n");
        close(socket_fd);
        socket_fd = -1;
        return -1;
    }


    printf("recv data: %s\n", recv_buff);
    //    for (i = 0; i < read_len; i++)
    //    {
    //        printf("%02x ", recv_buff[i]);
    //    }
    //    printf("\n");
    close(socket_fd);
    socket_fd = -1;
    return (EXIT_SUCCESS);
}
相关推荐
Irissgwe4 分钟前
进程间通信
linux·服务器·网络·c++·进程间通信
IT小白32 小时前
windows的VMware虚拟机上的Linux系统(CentOS)配置永久ip(关机重启ip不变)
网络·网络协议·tcp/ip
喵叔哟2 小时前
29_内容生产质量网关Skill:草稿生成+事实校验+发布前检查
网络·人工智能
小白橘颂3 小时前
【C语言】基础概念梳理(一)
c语言·开发语言·stm32·单片机·mcu·物联网·51单片机
co_wait3 小时前
【c 语言】linux下gcc编译工具的使用
linux·c语言·开发语言
liulilittle3 小时前
LINUX RING BUFFER TUN/TAP 1
linux·服务器·网络·c++·信息与通信·通信
always_TT3 小时前
结构体数组与初始化
c语言
蛊明3 小时前
批量检测 IP 是否在线:CPing vs QuickPing
网络·网络协议·tcp/ip
是翔仔呐4 小时前
第13章 超声波测距传感器驱动:HC-SR04底层原理与C语言实现
c语言·开发语言·单片机·嵌入式硬件·gitee
路由侠内网穿透.4 小时前
本地部署开源书签管理工具 LinkAce 并实现外部访问( Linux 版本)
linux·运维·服务器·网络·网络协议·开源