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
|
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define NPORT 9999
int main(int argc, char * argv[])
{
int sock;
struct sockaddr_in serveur_adr;
struct hostent *machine;
int length;
fd_set master;
FD_ZERO(&master);
FD_SET(STDIN_FILENO,&master);
int c;
int rval,rtval;
char *a;
a=malloc(sizeof(char)*1024);
char b[1033];
/*char *surnom;
char *PORT;*/
scanf("%s",a);
if(strncmp(a,"/connect",8)==0)
{
//creation socket modele TCP AF_INET
sock = socket (AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
perror("socket");
return 1;
}
//preparation adresse destination
bzero (&serveur_adr, sizeof(serveur_adr));
serveur_adr.sin_family = AF_INET;
serveur_adr.sin_port = htons(NPORT);
serveur_adr.sin_addr.s_addr = inet_addr ("127.0.0.1");
//connection distante
if (connect(sock, (struct sockaddr *)&serveur_adr, sizeof(serveur_adr)) < 0)
{
perror ("connect");
close (sock);
return 1;
}
while(1)
{
a=malloc(sizeof(char)*1024);
if (select(1, &master, NULL, NULL, NULL) == -1)
{
perror("select");
exit(1);
}
if(FD_ISSET(0,&master)) //si select n'a rien détecté, fd_isset -> faux,donc pas de read sur stdin
{
if(read(0,a,1024)>0)
{
if (write(sock,a,1024) < 0)
{
perror ("write");
close(sock);
return 1;
}
}
}
//ferme le client si "/quit" est tape
if(strncmp(a,"/quit",5)==0)
{
close(sock);
exit(0);
}
/*tandis que read est toujours pris en compte*/
if((rval = read (sock,b,sizeof(b))) < 0)
{
perror("read");
}
if(rval==0)
fprintf(stderr, "!!!!!!!!probleme!!!!!!\n");
if(strncmp(b,"/shutdown",9)==0)
{
close(sock);
fprintf(stdout,"le serveur a ete fermee\n");
return 0;
}
else
fprintf(stdout,"%s\n",b);
}
close (sock);
}
return 0;
} |
Partager