/* SYNOPSIS: servidorPrecio */ #include #include #include #include #include void reusePort(int sock); int main(int argc, char *argv[]) { fd_set readfds, readfdsCopy; int n; int actSock=0, cajaSock=0; struct addrinfo hints, *result, *rp; int as, cs; struct sockaddr_storage from_addr; socklen_t from_addr_len; char precio[50]; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; //IPv4 hints.ai_socktype = SOCK_STREAM; //TCP hints.ai_flags = AI_PASSIVE; //For wildcard IP address if ((getaddrinfo(NULL, argv[1], &hints, &result)) != 0) { fprintf(stderr, "getaddrinfo error\n"); exit(EXIT_FAILURE); } for (rp = result; rp != NULL; rp = rp -> ai_next) { as = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); reusePort(as); if (as == -1) continue; if (bind(as, rp -> ai_addr, rp -> ai_addrlen) == 0) break; //Success close(as); } memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; //IPv4 hints.ai_socktype = SOCK_STREAM; //TCP hints.ai_flags = AI_PASSIVE; //For wildcard IP address if ((getaddrinfo(NULL, argv[2], &hints, &result)) != 0) { fprintf(stderr, "getaddrinfo error\n"); exit(EXIT_FAILURE); } for (rp = result; rp != NULL; rp = rp -> ai_next) { cs = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); reusePort(cs); if (cs == -1) continue; if (bind(cs, rp -> ai_addr, rp -> ai_addrlen) == 0) break; //Success close(cs); } freeaddrinfo(result); //No longer needed listen(as,4); listen(cs,4); from_addr_len = sizeof(from_addr); FD_ZERO(&readfdsCopy); FD_SET(as,&readfdsCopy); FD_SET(cs,&readfdsCopy); for(;;){ memcpy(&readfds, &readfdsCopy, sizeof(fd_set)); n = select(FD_SETSIZE, &readfds, (fd_set *) 0, (fd_set *) 0, NULL); if (n > 0) { if (FD_ISSET(as, &readfds)) { printf("Accepting an Actualizador...\n"); actSock = accept(as, (struct sockaddr *) &from_addr, &from_addr_len); FD_SET(actSock, &readfdsCopy); } if (FD_ISSET(cs, &readfds)) { printf("Accepting a Caja...\n"); cajaSock = accept(cs, (struct sockaddr *) &from_addr, &from_addr_len); write(cajaSock, precio, strlen(precio)); } if (FD_ISSET(actSock, &readfds)) { if ((n=read(actSock, precio, sizeof(precio)))>0) { precio[n]='\0'; if (cajaSock > 0) write(cajaSock, precio, strlen(precio)); printf("precio: %s", precio); } else { close(actSock); FD_CLR(actSock, &readfdsCopy); } if (FD_ISSET(cajaSock, &readfds)) if ((n=read(cajaSock, precio, sizeof(precio)))<=0) { close(cajaSock); FD_CLR(cajaSock, &readfdsCopy); } } } } } void reusePort(int s) { int one=1; if ( setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *) &one,sizeof(one)) == -1 ) { printf("error in setsockopt,SO_REUSEPORT \n"); exit(-1); } }