1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/un.h>
#define MYPORT 9999
#define BACKLOG 5
#define MAXCLIENTS 1
#define MAXDATASIZE 100
int main(void)
{
int sockfd,new_fd,numbytes,highest = 0,i;
int clients[MAXCLIENTS];
int buffer[MAXDATASIZE] ;
struct sockaddr_in my_addr,their_addr;
socklen_t sin_size;
struct timeval tv;
fd_set readfds;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(-1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(MYPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero), 8);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(-1);
}
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(-1);
}
bzero(clients,sizeof(clients));
highest = sockfd ;
while(1) {
sin_size = sizeof(struct sockaddr_in);
tv.tv_sec = 0;
tv.tv_usec = 250000;
FD_ZERO(&readfds);
for ( i = 0 ; i < MAXCLIENTS ; i ++ ) {
if ( clients[i] != 0 ) {
FD_SET(clients[i],&readfds);
}
}
FD_SET(sockfd,&readfds);
if (select(highest+1, &readfds, NULL, NULL, &tv) >=0 ) {
if (FD_ISSET(sockfd, &readfds)) {
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) {
perror("accept");
continue;
}
for( i = 0 ; i < MAXCLIENTS ; i ++ ) {
if ( clients[i] == 0 ) {
clients[i] = new_fd ;
break;
}
}
if ( i != MAXCLIENTS ) {
if ( new_fd > highest ) {
highest = clients[i] ;
}
printf("Connexion received from %s (slot %i) ",inet_ntoa(their_addr.sin_addr),i);
send(new_fd,"Vous etes connecte au serveur",65,MSG_NOSIGNAL);
}
else {
send(new_fd, "No room for you ! ",18,MSG_NOSIGNAL);
close(new_fd);
}
}
for ( i = 0 ; i < MAXCLIENTS ; i ++ ) {
if ( FD_ISSET(clients[i],&readfds) ) {
if ( (numbytes=recv(clients[i],buffer,MAXDATASIZE,0)) <= 0 ) {
printf("Connexion lost from slot %i ",i);
close(clients[i]);
clients[i] = 0 ;
}
else {
buffer[numbytes] = '0';
printf("Received from slot %i : %s",i,buffer);
send(new_fd,buffer,10,MSG_NOSIGNAL);
}
}
}
}
else {
perror("select");
continue;
}
}
return 0;
} |