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
| #include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#define PORT 80
#define BACKLOG 5
#define MAXDATASIZE 2048
char buff[MAXDATASIZE];
int i;
int sockfd, newsockfd;
int pid, sin_size, nbytes;
struct sockaddr_in serveraddr; /* l'adreese de la socket serveur */
struct sockaddr_in clientaddr; /* l'adresse de la socket client */
struct hostent *hostinfo;
char *a;
int count;
pthread_t id;
int main()
{
int init_socket()
{
/*******CREATION DE SOCKET*******/
if ((sockfd=socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("création de socket impossible\n");
exit(1);
}
printf("socket créé\n");
/*******REMPLISSAGE DE LA SOCKET******/
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(PORT);
serveraddr.sin_addr.s_addr = INADDR_ANY; /* remplissage automatique */
/********ATTACHEMANT DE LA SOCKET AU N°PORT********/
if (bind(sockfd, (struct sockaddr*) &serveraddr,\
sizeof(struct sockaddr_in)) == 1)
{
exit(1);
}
printf("socket connecté au réseau\n");
/*******ECOUTE SUR LE RESEAU********/
if (listen(sockfd, BACKLOG) == -1)
{
exit(1);
}
}
int connexion()
{
/* attente permanente */
while(1) {
sin_size = sizeof(struct sockaddr);
if ((newsockfd=accept(sockfd,\
(struct sockaddr*) &clientaddr, &sin_size)) == -1)
{
exit(1);
}
printf ("client connecté\n");
/*************/
clientaddr.sin_family = AF_INET;
clientaddr.sin_port = 80;
memcpy((struct sockaddr*) &clientaddr.sin_addr.s_addr, hostinfo->h_addr, 4);
a = inet_ntoa(clientaddr.sin_addr);
printf(" adresse du client est: %s\n",a);
/********DUPLICATION DU PROCESSUS*******/
switch(pid=fork())
{
/** erreur de fork() **/
case(-1): close(sockfd);
close(newsockfd);
break;
/** libération de la socket d'écoute **/
case(0): close(sockfd);
{
fprintf(stdout, "requête n°:PID=%ld\n", (long) getpid());
if (nbytes=recv(newsockfd, buff, MAXDATASIZE,\
0) == -1)
{
exit(1);
}
printf("la ressource est: %s\n",&buff);
extraction();
if ((send(newsockfd, buff, MAXDATASIZE, 0)) == -1)
{
printf("echec\n");
exit(1);
}
}
}
}
} |
Partager