Untitled
unknown
plain_text
2 years ago
2.7 kB
3
Indexable
Never
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main(void) { fd_set master; fd_set read_fds; struct sockaddr_in myaddr; struct sockaddr_in remoteaddr; int fdmax; int listener; int newfd; char buf[256]; int nbytes; int yes=1; int addrlen; int i; FD_ZERO(&master); FD_ZERO(&read_fds); if ((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(int)) == -1) { perror("setsockopt"); exit(1); } myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); myaddr.sin_port = htons(33601); memset(&(myaddr.sin_zero), '\0', 8); if (bind(listener, (struct sockaddr *)&myaddr, sizeof(myaddr)) == -1) { perror("bind"); exit(1); } if (listen(listener, 10) == -1) { perror("listen"); exit(1); } FD_SET(listener, &master); fdmax = listener; while (1) { read_fds = master; if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) { perror("select"); exit(1); } for(i = 0; i <= fdmax; i++) { if (FD_ISSET(i, &read_fds)) { if (i == listener) { addrlen = sizeof(remoteaddr); if ((newfd = accept(listener, (struct sockaddr *)&remoteaddr,&addrlen)) == -1) perror("accept"); else { FD_SET(newfd, &master); // if (newfd > fdmax) fdmax = newfd; printf("utworzono nowe polaczenieni z %s, socket %d\n", inet_ntoa(remoteaddr.sin_addr), newfd); } } if (i != listener) { nbytes = recv(i,buf,sizeof(buf),0); if (nbytes <= 0) { if (nbytes == 0) printf("Klient %d rozlaczyl sie\n",i); if (nbytes < 0) perror("recv"); close(i); FD_CLR(i, &master); } else puts(buf); } } } } return 0; }