功能:实现一个简单的tcp客户端,连接本地端口8888的tcp服务端,并发送一条报文。
/* * 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);
}