[Subject Prev][Subject Next][Thread Prev][Thread Next][Subject Index][Thread Index]
program using select
/* MULTIPLEXING SOCKETS USING SELECT */
#include<stdlib.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<sys/select.h>
#include<sys/time.h>
#define max(a,b) ((a) > (b) ? (a) : (b))
#define PORTA 8000
#define PORTB 6000
struct sockaddr_in serv_addr1,serv_addr2,client;
int main()
{
int sockfd1,sockfd2,count=0,length=0,maxfd1;
char buff1[128],buff2[128];
fd_set set;
struct timeval time;
socklen_t addrlen=sizeof(client);
FD_ZERO(&set);
time.tv_sec = 5;
time.tv_usec = 0;
printf("reciever running\n");
serv_addr1.sin_family=AF_INET;
serv_addr1.sin_addr.s_addr=inet_addr("127.0.0.1");
serv_addr1.sin_port=htons(PORTA);
if((sockfd1=socket(AF_INET,SOCK_DGRAM,0))<0)
write("I/O socket error/n");
if((bind(sockfd1,(struct sockaddr *)&serv_addr1,sizeof(serv_addr1)))<0)
printf("bind error/n");
serv_addr2.sin_family=AF_INET;
serv_addr2.sin_addr.s_addr=inet_addr("127.0.0.1");
serv_addr2.sin_port=htons(PORTB);
if((sockfd2=socket(AF_INET,SOCK_DGRAM,0))<0)
write("I/O socket error/n");
if((bind(sockfd2,(struct sockaddr *)&serv_addr2,sizeof(serv_addr2)))<0)
printf("bind error/n");
for(;;)
{
FD_SET(sockfd1,&set);
FD_SET(sockfd2,&set);
maxfd1 = max(sockfd1,sockfd2) + 1;
select(maxfd1,&set,&set,NULL,&time);
if(FD_ISSET(sockfd1,&set))
{
count = recvfrom(sockfd1,(char *)buff1,sizeof(buff1),0,
(struct sockaddr *)&client,&addrlen);
printf("\n %s ",buff1);
}
if(FD_ISSET(sockfd2,&set))
{
count = recvfrom(sockfd2,(char *)buff2,sizeof(buff2),0,
(struct sockaddr *)&client,&addrlen);
printf("\n %s ",buff2);
}
}
}