标签:bin lis socket server return main ror 简单的 简单
#include <stdio.h>
#include <ctype.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#define SERVER_PORT 7000
void sys_err(const char *str)
{
perror(str);
exit(1);
}
int main(int agrc, char *argv[]){
int ret;
char buf[BUFSIZ];
// 创建文件描述符
int lfd = 0, cfd=0;
// 创建addr地址的结构体
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
// 创建socket
lfd = socket(AF_INET, SOCK_STREAM, 0);
if(lfd == -1){
sys_err("socket error");
}
// 绑定端口
bind(lfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
// 设置监听
listen(lfd, 128);
// 堵塞等待
client_addr_len = sizeof(client_addr);
cfd = accept(lfd, (struct sockaddr *)&client_addr, &client_addr_len);
if (cfd == -1){
sys_err("accept error");
}
while(1){
// 读取内容
ret = read(cfd, buf, sizeof(buf));
write(STDOUT_FILENO, buf, ret);
for (int i=0; i<ret; i++){
buf[i] = toupper(buf[i]);
}
write(cfd, buf, ret);
}
close(lfd);
close(cfd);
return 0;
}
标签:bin lis socket server return main ror 简单的 简单
原文地址:https://www.cnblogs.com/fandx/p/12151455.html