1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<string.h>
#include<netinet/in.h>
#include<fcntl.h>
#include<netdb.h>
#include<unistd.h>
#define MAX 100
#define SA struct sockaddr
#define SERV_PORT 2001
void func(int sockfd)
{
char buf[MAX],bufrev[MAX];
int i,j;
for(;;)
{
read(sockfd,buf,sizeof(buf));
printf("from client :%s\n",buf);
for(i=strlen(buf),j=0;i>=0;i--)
{
if(buf[i]!='\0')
bufrev[j++]=buf[i];
}
bufrev[j]='\0';
//printf("reverse string is %s",bufrev);
write(sockfd,bufrev,strlen(bufrev));
}}
int main()
{
int listenfd,connfd,sockfd;
pid_t childpid;
socklen_t clilen;
struct sockaddr_in cliaddr,servaddr;
listenfd=socket(AF_INET,SOCK_STREAM,0);
if(listenfd==-1)
{
printf("socket creation failed");
exit(0);
}
else
printf("socket successfully created");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_family=htonl(INADDR_ANY);
servaddr.sin_port=htons(SERV_PORT);
bind(listenfd,(SA *)&servaddr,sizeof(servaddr));
listen(listenfd,5);
printf(" ser list");
clilen=sizeof(cliaddr);
connfd=accept(listenfd,(SA *)&cliaddr,&clilen);
if(connfd==-1)
{
printf("server accept failed");
exit(0);
}
else
printf("server accept client");
if((childpid=fork())==0)
{
func(connfd);
close(connfd);
exit(0);
}
close(connfd);
}
|