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;
}
o/p in the client
Enter the message to send , Enter # to exit :
this is test-> this is the message you typed .
Received following message : this is test
o/p in the server
Server waiting for new connection :
Received ans sent the following message : this is test
v1gnesh said:^. you ran each prog on a diff comp for this :| ?
and yeah i know it is the basics of socket programming
remember the fact that im just entering 2nd yr and i guess this comes in 4/5th sem :S
Start the server first
Then the client .Both on the same machine
Type some message in the client.
The messgae shlud be recied by the server and then server
sends this message back to the client .