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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
| #include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <inttypes.h>
#include <fcntl.h>
#include <sys/time.h>
#include <string.h>
#include <sys/select.h>
main(int argc, char ** argv)
{
//DECLARATIONS DE VARIABLES
struct sockaddr_in serv ;
struct sockaddr_in client ;
int port ;
int s ;
int a[50] ;
char buf ;
int lg = sizeof(client) ;
int reponse ;
int dfichier ;
int nb ;
int nr ;
int k ;
int j ;
fd_set readfds ;
int nfds ;
int max ;
int continu ;
serv.sin_family = AF_INET ;
sscanf(argv[1], "%d" ,&port ) ;
serv.sin_port = htons(port) ;
serv.sin_addr.s_addr = htonl(INADDR_ANY) ;
//ON CREER LA SOCKET
if((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))<0)
{
perror("erreur création socket") ;
exit(-4) ;
}
printf("Serveur TALK lancé sur le port %s \n", argv[1]) ;
//ON LIE LA SOCKET A LA STRUCTURE SOCKADDR
if(bind(s,(struct sockaddr *) &serv,sizeof(serv))<0)
{
perror("erreur socket") ;
exit(-5) ;
}
//ON LIMITE LE NOMBRE DE CONNEXION A 5
if(listen(s,5)<0)
{
perror("erreur listen") ;
exit(-6) ;
}
//ON MET EN PLACE UN TABLEAU QUI CONTIENDRA TOUS LES DESCRIPTEURS
nb=0 ;
a[nb]=s ;
nb++ ;
FD_ZERO(&readfds) ;
FD_SET(s, &readfds) ;
while(1)
{
for(j=0, max=a[0] ; j<nb;j++)
{
if(a[j]>max)
max=a[j] ;
}
nfds=max+1 ;
fd_set readfds2 = readfds ;
if(select(nfds, &readfds2,0,0,0)==-1)
{
perror("erreur select") ;
exit(-9) ;
}
else
for(k=0; k<nb ; k++)
{
if(FD_ISSET(a[k],&readfds2))
{
if(a[k]==s)
{
if ((a[nb] = accept(s,(struct sockaddr *)&client,&lg))==-1)
{
perror("erreur accept") ;
exit(-7) ;
}
else
{
printf("client accepté\n") ;
FD_SET(a[nb], &readfds) ;
nb++ ;
}
}
else
{
while(read(a[k],&buf, 1)>0)
write(1,&buf,1) ;
}
}
}
}
close(s) ;
} |
Partager