hello....i am trying to establish a communication between server and client and later to do some communication between them, so first i am trying to establish communication and i see that server gives "segmentation fault" as the output. I am placing the code below, check it out and let me know where the errors are.
Server Program :
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MYPORT 51005
#define BACKLOG 10
#define MAXDATASIZE 1000
int main(int argc, char* argv[])
{
int sockfd, numbytes, abcd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
char buf[MAXDATASIZE];
char *string;
int sin_size;
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
exit(EXIT_FAILURE);
}
// Loading all the address values of the socket into the structure
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(MYPORT);
my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */
bzero(&(my_addr.sin_zero), 8);
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1)
{
perror("bind");
exit(EXIT_FAILURE);
}
if(listen(sockfd,BACKLOG)==-1)
{
perror("listen");
exit(EXIT_FAILURE);
}
sin_size = sizeof(struct sockaddr_in);
if(accept(sockfd,(struct sockaddr *)&their_addr,(socklen_t*)&sin_size)==-1)
{
perror ("accept");
exit(EXIT_FAILURE);
}
else
printf("\n connection established with the client %s",their_addr);
close(sockfd);
return 0;
}
Client Program :
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/time.h>
//#define PORT 51005
#define MAXDATASIZE 1000
int main()
{
int sockfd, numbytes, PORT;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in their_addr;
// As all processes are in the same system connection is made to localhost
if ((he=gethostbyname("localhost")) == NULL)
{
herror("gethostbyname");
exit(EXIT_FAILURE);
}
// A connection is being established for the process to the socket
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(EXIT_FAILURE);
}
// Loading all the address values of the socket into the structure
printf("Enter the port number : ");
scanf("%d", &PORT);
their_addr.sin_family = AF_INET;
their_addr.sin_port = htons(PORT);
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
bzero(&(their_addr.sin_zero), 8);
// Connection is established between the processes using sockets using connect()
if (connect(sockfd,(struct sockaddr *)&their_addr, sizeof(struct sockaddr)) ==-1)
{
perror("connect");
exit(EXIT_FAILURE);
}
else printf("\n connection established");
/*while(1)
{
if((numbytes=recv(sockfd, buf, MAXDATASIZE, 0)) == -1)
{
perror("recv");
exit(EXIT_FAILURE);
}
buf[numbytes] = '\0';
printf("\n %s", buf);
}*/
close(sockfd);
return 0;
}