功能:实现一个简单的tcp客户端,连接本地端口8888的tcp服务端,并发送一条报文。
文章来源地址https://www.toymoban.com/news/detail-623507.html
/*
* 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);
}
文章来源:https://www.toymoban.com/news/detail-623507.html
到了这里,关于c语言实现简单的tcp客户端的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!