c语言tcp通信demo
时间: 2023-03-28 12:01:52 浏览: 175
基于C语言的tcp demo
你好,以下是一个简单的 C 语言 TCP 通信的示例代码:
服务端代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define MAXLINE 1024
int main() {
int sockfd, connfd;
struct sockaddr_in servaddr, cliaddr;
char buff[MAXLINE];
int n;
sockfd = socket(AF_INET, SOCK_STREAM, );
if (sockfd == -1) {
perror("socket");
exit(1);
}
memset(&servaddr, , sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
if (bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) {
perror("bind");
exit(1);
}
if (listen(sockfd, 10) == -1) {
perror("listen");
exit(1);
}
printf("server listening on port %d...\n", PORT);
while (1) {
socklen_t len = sizeof(cliaddr);
connfd = accept(sockfd, (struct sockaddr *)&cliaddr, &len);
if (connfd == -1) {
perror("accept");
continue;
}
printf("client connected: %s:%d\n", inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port));
while ((n = recv(connfd, buff, MAXLINE, )) > ) {
buff[n] = '\';
printf("received: %s", buff);
send(connfd, buff, n, );
}
if (n == ) {
printf("client closed connection\n");
} else {
perror("recv");
}
close(connfd);
}
close(sockfd);
return ;
}
```
客户端代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define MAXLINE 1024
int main() {
int sockfd;
struct sockaddr_in servaddr;
char buff[MAXLINE];
int n;
sockfd = socket(AF_INET, SOCK_STREAM, );
if (sockfd == -1) {
perror("socket");
exit(1);
}
memset(&servaddr, , sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127...1");
servaddr.sin_port = htons(PORT);
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) {
perror("connect");
exit(1);
}
printf("connected to server: %s:%d\n", inet_ntoa(servaddr.sin_addr), ntohs(servaddr.sin_port));
while (fgets(buff, MAXLINE, stdin) != NULL) {
send(sockfd, buff, strlen(buff), );
n = recv(sockfd, buff, MAXLINE, );
if (n == -1) {
perror("recv");
exit(1);
} else if (n == ) {
printf("server closed connection\n");
break;
} else {
buff[n] = '\';
printf("received: %s", buff);
}
}
close(sockfd);
return ;
}
```
希望对你有帮助。
阅读全文