#include#include#include#include#include#include#include#include#include#definePORT1234#defineBACKLOG5#defineMAXDATASIZE1000voidprocess_cli(intconnfd,structsockaddr_inclient);intmain(){intlistenfd,connfd;pid_tpid;structsockaddr_inserver;structsockaddr_inclient;intlen;if((listenfd=socket(AF_INET,SOCK_STREAM,0))==-1){perror("Creatingsockfalied");exit(1);}intopt=SO_REUSEADDR; setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)); bzero(&server,sizeof(server)); server.sin_family=AF_INET; server.sin_port=htons(PORT); server.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(listenfd,(structsockaddr*)&server,sizeof(server))==-1){ perror("Binderror"); exit(1); } if(listen(listenfd,BACKLOG)==-1){ perror("listen()error\n"); exit(1); } len=sizeof(client); while(1){ if((connfd=accept(listenfd,(structsockaddr*)&client,&len))==-1){ perror("accept()error\n"); exit(1); } if((pid=fork())>0){ close(connfd); continue; }elseif(pid==0){ close(listenfd); process_cli(connfd,client); exit(0); }else{ printf("fork()error\n"); exit(0); } } close(listenfd);}voidprocess_cli(intconnfd,structsockaddr_inclient){ intnum; charrecvbuf[MAXDATASIZE],sendbuf[MAXDATASIZE],cli_name[MAXDATASIZE]; printf("Yougotaconnectionfrom%s.\n",inet_ntoa(client.sin_addr)); num=recv(connfd,cli_name,MAXDATASIZE,0); if(num==0){ close(connfd); printf("Clientdisconnected.\n"); return; } cli_name[num-1]='\0'; printf("Client'snameis%s.\n",cli_name);printf("Client'sportis%d.\n",ntohs(client.sin_port)); while(num=recv(connfd,recvbuf,MAXDATASIZE,0)){ recvbuf[num]='\0'; //printf("Receivedclient(%s)message:%s",cli_name,recvbuf);if(!strcmp(recvbuf,"quit")){//判断用户输入的是否是quitbreak;} inti=0; for(i=0;i='a'&&recvbuf='A'&&recvbuf'Z'&&recvbuf'z')) recvbuf=recvbuf-26; } sendbuf=recvbuf; } sendbuf[num-1]='\0';printf("Theencryptedmessagefromclient(%s)is:%s\n",cli_name,sendbuf); send(connfd,sendbuf,strlen(sendbuf),0); } close(connfd);} |