对一段C语言服务器代码的详解
- 服务端----其代码如下
#include <stdio.h> #include<stdlib.h> #include<sys/socket.h> #include<unistd.h> #define SERV_PORT 9898 #define SERV_IP "127.0.0.1" #include<ctype.h> #include<arpa/inet.h> int main() { int lfd,cfd,n,i; char buf[BUFSIZ]; struct sockaddr_in serv_addr,client_addr; socklen_t client_addr_len; lfd=socket(AF_INET,SOCK_STREAM,0);// serv_addr.sin_family=AF_INET; serv_addr.sin_port=htons(SERV_PORT); serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);// bind(lfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)); listen(lfd,128);//128 is uplimit client_addr_len=sizeof(client_addr); cfd=accept(lfd,(struct client_addr*)&client_addr,&client_addr_len);//will recv fd and return fd while(1) { n=read(cfd,buf,sizeof(buf)); for(i=0;i<n;i++) { buf[i]=toupper(buf[i]); } write(cfd,buf,n); } printf("Hello World!\n"); return 0; }
测试:打开一个终端输入 nc 127.0.0.1 9898
- 客户端
#include<stdio.h> #include<arpa/inet.h> #include<stdlib.h> #include<unistd.h> #include<sys/socket.h> #include<string.h> #define SERV_IP "127.0.0.1" #define SERV_PORT 9898 int main() { int cfd,n; char buf[BUFSIZ]; struct sockaddr_in serv_addr; socklen_t serv_addr_len; memset(&serv_addr,0,sizeof(serv_addr)); cfd=socket(AF_INET,SOCK_STREAM,0); serv_addr.sin_family=AF_INET; serv_addr.sin_port=SERV_PORT; inet_pton(AF_INET,SERV_IP,&serv_addr.sin_addr.s_addr); connect(cfd,(struct sockaddr_in *)&serv_addr,sizeof(serv_addr)); while(1) { fgets(buf,sizeof(buf),stdin);//gets is out-of-date;use fgets readline until the end, back with \0 write(cfd,buf,strlen(buf)); n=read(cfd,buf,sizeof(buf)); write(STDOUT_FILENO,buf,n); } close(cfd); return 0; }
相关推荐
chensen 2020-11-14
拉斯厄尔高福 2020-11-04
杜倩 2020-10-29
拉斯厄尔高福 2020-10-19
嵌入式资讯精选 2020-10-15
zhaochen00 2020-10-13
penkgao 2020-10-13
yiyilanmei 2020-10-05
wanshiyingg 2020-09-29
Mars的自语 2020-09-27
shenwenjie 2020-09-24
一个逗逗 2020-09-22
flycony 2020-09-13
zhaochen00 2020-08-20
Biao 2020-08-20
qingsongzdq 2020-08-19
penkgao 2020-08-17
cetrolchen 2020-08-14
GuoSir 2020-08-07