Server Code
--------------
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#define SRV_TCP_PORT 27000 //port on which the server will be listening
#define MAX_MSG 100
void errExit(char *str)
{
puts(str);
exit(0);
}
int main()
{
int sockfd, newsockfd;
struct sockaddr_in cliadr, srvadr;
int clilen, n;
char mesg[MAX_MSG];
/*initialise the socket library*/
if((sockfd = socket(AF_INET, SOCK_STREAM, 0))<0)
errExit(" Can't open stream socket ");
/* bind server port */
memset(&srvadr,0,sizeof(srvadr));
srvadr.sin_family = AF_INET;
//allows you to recieve packets irrespective of ip Adress
srvadr.sin_addr.s_addr = htonl(INADDR_ANY);
//this is the port on which socket will be listening for connections
srvadr.sin_port = htons(SRV_TCP_PORT);
/*The bind() function associates a local address with a socket*/
if(bind(sockfd, (struct sockaddr*) &srvadr, sizeof(srvadr))<0)
errExit(" Can't bind local address");
//listen for connections
listen(sockfd,5);
while(1)
{
printf(" Server waiting for new connection : \n");
//if a client tries to connect on the port the server accepts the connection
//clilen = sizeof(cliaddr);
newsockfd = accept(sockfd, (struct sockaddr*) &cliadr, &clilen);
if(newsockfd<0)
errExit(" Accept Error \n");
printf("connected to the client \n");
/* receive segments */
while(1)
{
//recieve the message sent by the client
n = recv(newsockfd,mesg,MAX_MSG,0);
if(n<0)
errExit(" Receive Error \n");
if(n==0)
{
close(newsockfd);
break;
}
//send a message same message to the client
if(send(newsockfd,mesg,n,0) != n)
errExit(" Send Error \n");
printf(" Received ans sent the following message : %s \n", mesg);
} /* while(read_line) */
} /* while(1) */
return 0;
}