I have been trying to establish a local client server using UNIX sockets and here are the two programs. After I run the server program on terminal, it shows "The socket was created" and "Binding Socket" but soon after when I run the client side program, and send the IP (127.0.0.1) as argument for it, the server program crashes with "Segmentation fault (core dumped)". Please help rectify.
Server Side->
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<fcntl.h>
int main(int argc,char *argv[])
{
int create_socket,new_socket,addrlen,cont,fd;
int bufsize=1024;
char *buffer=malloc(bufsize);
char fname[256];
struct sockaddr_in address;
if((create_socket=socket(AF_INET,SOCK_STREAM,0))>0)
printf("the socket was created\n");
address.sin_family=AF_INET;
address.sin_addr.s_addr=INADDR_ANY;
address.sin_port=htons(15000);
if(bind(create_socket,(struct sockaddr *)&address,sizeof(address))==0)
printf("binding socket \n");
listen(create_socket,3);
addrlen=sizeof(struct sockaddr_in);
new_socket=accept(create_socket,(struct sockaddr*)&address,&addrlen);
if(new_socket>0)
printf("the client %s is connected...\n",inet_ntoa(address.sin_addr));
recv(new_socket,fname,255,0);
printf("a request for filename %s received\n",fname);
if((fd=open(fname,O_RDONLY))<0)
{
perror("file open failed ");
exit(0);
}
while((cont=read(fd,buffer,bufsize))>0)
{
send(new_socket,buffer,cont,0);
}
printf("request completed \n");
close(new_socket);
return close(create_socket);
}
Client Side->
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
int main(int argc,char *argv[])
{
int create_socket,cont;
int bufsize=1024;
char *buffer=malloc(bufsize);
char fname[256];
struct sockaddr_in address;
if((create_socket=socket(AF_INET,SOCK_STREAM,0))>0)
printf("the socket was created\n");
address.sin_family=AF_INET;
address.sin_port=htons(15000);
inet_pton(AF_INET,argv[1],&address.sin_addr);
if(connect(create_socket,(struct sockaddr*)&address,sizeof(address))==0)
printf("the connection was accepted with the server %s",argv[1]);
printf("enter the filename to request :");
scanf("%s",fname);
send(create_socket,fname,sizeof(fname),0);
printf("request accepted .... receiving file \n");
printf("the contents of file are... \n");
while((cont=recv(create_socket,buffer,bufsize,0))>0)
{
write(1,buffer,cont);
}
printf("\n EOF\n");
return close(create_socket);
}
