Write A C-Program To Demonstrate Socket For Stream Server.

Demonstrate Socket For Stream Server.
include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<errno.h>
#include<netinet/in.h>
main(int argc,char *argv[])
{
int sockfd,newfd,child,nbytes,nbyte;
struct sockaddr_in myaddr;
char buff[512];
if(argc!=2)
{
printf("usage: server port\n");
}
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket failed");
}
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(atoi(argv[1]));
myaddr.sin_addr.s_addr=htonl(0);
if(bind(sockfd,(struct sockaddr *) &myaddr,sizeof(myaddr))<0)
{
perror("bind failed");
}
if(listen(sockfd,5)<0)
{
perror("listen failed");
}
for( ; ; )
{
if((newfd=accept(sockfd,0,0))<0)
PAGE NO.
47
47
SWARNA BHARATHI COLLEGE OF ENGINEERING MCA III SEM
{
perror("accept failed");
}
if((child=fork())<0)
{
perror("fork failed");
}
if(child==0)
{
close(sockfd);
while((nbytes=read(newfd,buff,512))!=0)
{
if(nbytes<0)
{
perror("read eroor");
}
nbyte=sizeof(buff);
if(write(newfd,buff,nbytes)!=nbytes)
{
perror(" write failed:server");
}
}
}
}
}
Demonstrate Socket For Stream Server.

Related post