hi all,
i started learning socket's
tried to write a simple client server under unix
and got a runtime error
i run the server and client on to shells (internal network \ localhost \ whatever)
after sending the message the client (sending) throws this: Illegal instruction (core dumped)
and the server receiving throws: Segmentation fault (core dumped)
the server code
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main ()
{
int socketfd , incomfd, err;
struct sockaddr_in myip;
struct sockaddr_in hisip;
int sin_size;
int bytes_recv, len=20, backlog=5;
char buff[40];
int myport=55555;
socketfd = socket(PF_INET , SOCK_STREAM , 0);
if(socketfd==-1)
{printf("unable to creat socket!!");
exit(1);
}
// intilaize myip address structer
myip.sin_family = AF_INET;
myip.sin_port = htons(myport);
myip.sin_addr.s_addr =INADDR_ANY; //inet_addr("127.0.0.1"); // this ip address is for the loopback network (internal ip address).
memset(myip.sin_zero, '\0', sizeof (myip.sin_zero));
err=bind ( socketfd , (struct sockaddr *) &myip , sizeof(myip));
if(err==-1)
{printf("unable to use port... bind()");
exit(1);
}
err=listen(socketfd , backlog);
if(err==-1)
{printf("error listening");
exit(1);
}
sin_size = sizeof (hisip);
incomfd= accept(socketfd , (struct sockaddr *) &hisip , &sin_size);
if(incomfd==-1)
{printf("error accepting!");
exit(1);
}
bytes_recv=recv(incomfd , buff , len , 0);
printf("bytes recived: %d",bytes_recv);
if(bytes_recv==-1)
{printf("error while recieving");
exit(1);
}
close(socketfd);
printf("The message recieved: %s \n", *buff);
return 0;
}
the client code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main ()
{
int socketfd;
struct sockaddr_in destip;
int destport = 55555;
int err ,sent_bytes, len;
char *msg;
socketfd = socket( PF_INET , SOCK_STREAM , 0);
if(socketfd==-1)
{printf("couldn't creat socket!!");
exit(1);
}
destip.sin_family = AF_INET;
destip.sin_port = htons(destport);
destip.sin_addr.s_addr =INADDR_ANY; //inet_addr("127.0.0.1");
memset(destip.sin_zero, '\0', sizeof (destip.sin_zero));
err=connect( socketfd , (struct sockaddr *) &destip , sizeof(destip));
if (err==-1)
{printf("couldn't connect!");
exit(1);
}
printf("Enter the message to send: \n");
gets(msg);
len=strlen(msg);
printf("The message is %s \n and it is %d charecters long \n",msg , len);
sent_bytes= send( socketfd , msg , len , 0);
printf("bytes sent %d\n", sent_bytes);
close(socketfd);
return 0;
}
i really cant figure what am i doing wrong
please direct me to the write direction
thanx