C语言中的TCP通信服务端例程代码
时间: 2023-04-07 18:04:13 浏览: 146
我可以回答这个问题。以下是一个简单的C语言TCP通信服务端例程代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8888
#define MAXLINE 1024
int main(int argc, char *argv[]) {
int listenfd, connfd;
struct sockaddr_in servaddr, cliaddr;
socklen_t cliaddr_len;
char buf[MAXLINE];
char str[INET_ADDRSTRLEN];
int i, n;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
listen(listenfd, 20);
printf("Accepting connections ...\n");
while (1) {
cliaddr_len = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddr_len);
inet_ntop(AF_INET, &cliaddr.sin_addr, str, sizeof(str));
printf("Received a connection from %s\n", str);
while (1) {
n = read(connfd, buf, MAXLINE);
if (n == 0) {
printf("The client %s closed the connection\n", str);
break;
}
printf("Received message from %s: %s", str, buf);
for (i = 0; i < n; i++) {
buf[i] = toupper(buf[i]);
}
write(connfd, buf, n);
}
close(connfd);
}
return 0;
}
```
这个例程实现了一个简单的TCP通信服务端,监听在8888端口上。当有客户端连接时,服务端会打印出客户端的IP地址,并接收客户端发送的消息,将消息转换为大写后发送回客户端。
阅读全文