您的位置:首页 > 财经 > 产业 > Linux下的简单TCP客户端和服务器

Linux下的简单TCP客户端和服务器

2024/11/16 19:17:10 来源:https://blog.csdn.net/weixin_74027669/article/details/142284433  浏览:    关键词:Linux下的简单TCP客户端和服务器

客户端

#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>int main()
{struct sockaddr_in* caddr=(struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));caddr->sin_port = htons(8999);inet_pton(AF_INET, "192.168.101.231", &caddr->sin_addr.s_addr);caddr->sin_family = AF_INET;int cfd = socket(AF_INET, SOCK_STREAM, 0);if (cfd == -1){perror("socket error");return 1;}int res = connect(cfd, (struct sockaddr*)caddr, sizeof(struct sockaddr));if (res == -1){perror("connect error");return 1;}while (1){char buf[1024] = {'\0'};int res = send(cfd, "this is client", strlen("this is client"), 0);if (res != -1){printf("send:%s\n", "this is client");}else{perror("send error");}res = recv(cfd, buf, 1024, 0);if (res == -1){perror("recv error");}else{printf("client recv:%s\n", buf);}memset(buf, 0, 1024);}close(cfd);return 0;
}

服务器

#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>int main()
{struct sockaddr_in saddr;saddr.sin_port = htons(8999);saddr.sin_addr.s_addr = INADDR_ANY;saddr.sin_family = AF_INET;int sfd = socket(AF_INET, SOCK_STREAM, 0);if (sfd == -1){perror("socket error");return 1;}int bind_res = bind(sfd, (struct sockaddr*)&saddr, sizeof(struct sockaddr_in));if (bind_res == -1){perror("bind error");return 1;}listen(sfd, 100);int size = sizeof(struct sockaddr_in);int cfd = accept(sfd, (struct sockaddr*)&saddr, (socklen_t*)&size);while (1){if (cfd == -1){perror("accept error");return 1;}char buf[1024] = {'\0'};int res = recv(cfd, buf, 1024, 0);if (res != -1){printf("recv:%s\n", buf);}strcat(buf, ": is recved by server");res = send(cfd, buf, strlen(buf), 0);if (res == -1){perror("send error");}memset(buf, 0, 1024);}close(cfd);close(sfd);return 0;
}

运行结果:

客户端:

服务器

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com