Code:
// Here Data sending order goes like this.
// First Client 1 then client 2 has to send data to server for recognization.
// Then Client 2 has to start conversation then client1 , client2...
// in this order data has to be sent.
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define MAXSIZE 25
main()
{
struct sockaddr_in ss_addr, c_addr,c1_addr, c2_addr ;
int sockfd, rval, addr_len, addr_len1;
char buff[MAXSIZE], buff1[MAXSIZE];
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1 )
printf("socket(logical port) creation error");
//printf("bef");
ss_addr.sin_family = AF_INET;
ss_addr.sin_port = htons(7035);
ss_addr.sin_addr.s_addr = htonl(INADDR_ANY);
rval = bind(sockfd, (struct sockaddr*) &ss_addr, sizeof(ss_addr) );
//printf("hHHHH");
if (rval == -1)
{ printf( "Binding error");close(sockfd);}
else
{
// printf("in else");
addr_len = sizeof(c_addr);
addr_len1 = sizeof(c1_addr);
rval = recvfrom(sockfd, buff, sizeof(buff), 0, (struct sockaddr*)&c_addr, &addr_len );
if (rval == -1)
printf("while recving from 1st problem.");
puts(buff);
rval = recvfrom(sockfd, buff1, sizeof(buff1), 0, (struct sockaddr*)&c1_addr, &addr_len1 );
puts(buff1);
while(1)
{
// For Client 2
rval = recvfrom(sockfd, buff1, sizeof(buff1), 0, (struct sockaddr*)&c1_addr, &addr_len1 );
if (rval == -1)
{ printf("while recving from 2nd problem.");close(sockfd);}
puts(buff1);
rval = sendto(sockfd, buff1, sizeof(buff1), 0, (struct sockaddr*)&c_addr, addr_len );
if (rval == -1)
printf("while sending from server to 1st client problem.");
// For Client 1
rval = recvfrom(sockfd, buff, sizeof(buff), 0, (struct sockaddr*)&c_addr, &addr_len );
if (rval == -1)
{ printf("while recving from 1st problem.");close(sockfd);}
puts(buff);
rval = sendto(sockfd, buff, sizeof(buff), 0, (struct sockaddr*)&c1_addr, addr_len1 );
if (rval == -1)
{ printf("while sending from server to 2nd client problem.");close(sockfd);}
if (rval == -1)
{ printf("breaking from loop ");close(sockfd);
break;
}
} // while end
// printf("at end");
// puts(buff);
}
close(sockfd);
}