chat.c

Go to the documentation of this file.
00001 
00026 #include <sys/types.h>
00027 #include <sys/socket.h>
00028 #include <sys/stat.h>
00029 #include <netinet/in.h>
00030 #include <netdb.h>
00031 #include <stdio.h>
00032 #include <string.h>
00033 #include <stdlib.h>
00034 
00035 #define TAMMSG 80
00036 
00045 int main(int argc, char *argv[])
00046 {
00047 
00048   int s1;
00049 
00050   struct sockaddr_in server;
00051   struct hostent *hp, *gethostbyname();
00052 
00053   char msg_rec[TAMMSG] ;
00054   char msg_send[TAMMSG] ;
00055   int rval;
00056 
00057   if (argc < 3) {
00058      printf("Erro uso correto:\n") ;
00059      printf("\n    %s <hostname> <portnumber>\n\n", argv[0]) ;
00060      exit(1) ;
00061   }
00062     
00063   s1=socket(AF_INET, SOCK_STREAM, 0);
00064 
00065   if (s1<0) {
00066      perror("opening stream socket");
00067      exit(1);
00068   }
00069 
00070   hp = gethostbyname(argv[1]);
00071   if (hp == 0) {
00072      fprintf(stderr,"%s: Unkown host\n",argv[1]);
00073      exit(2);
00074   }
00075   
00076   server.sin_family = AF_INET;
00077   server.sin_port = htons(atoi(argv[2]));
00078   server.sin_addr = *((struct in_addr *)hp->h_addr);
00079   memset(&(server.sin_zero), '\0', 8);  // zero the rest of the struct 
00080     
00081 
00082   if (connect(s1, (struct sockaddr *)&server, sizeof server ) < 0) {
00083     perror("connectando stream socket");
00084     exit(1);
00085   }
00086 
00087   printf("\nConexao Estabelecida.\n") ;
00088   
00089   do {
00090 
00091                  //recebe mensagem...
00092                  printf("\n:>");
00093                  rval = recv(s1, msg_rec, TAMMSG, 0) ;
00094          msg_rec[rval] = 0;
00095                  printf("%s\n",msg_rec);
00096                  if(strcmp(msg_rec, "quit")==0) {
00097                          printf("bye.\n");
00098                          send(s1, "quit", strlen("quit"), 0);
00099                          break;
00100                  }
00101 
00102          //envia mensagem...
00103          printf("\nTalk>") ;
00104          fgets(msg_send,TAMMSG,stdin);//pega a informação do terminal.
00105          //printf("Enviei: %s\n",msg_send);
00106          //sprintf(msg,"%s\n",msg);
00107                  send(s1, msg_send, strlen(msg_send), 0);
00108                  if(strcmp(msg_send, "quit")==0){
00109                          printf("bye.\n");
00110                          send(s1, "quit", strlen("quit"), 0);
00111                          break;
00112                  }
00113                  
00114   } while (msg_send[0] != '.' && rval != 0);
00115 
00116   printf("\nFim da conexao.\n");
00117   close(s1);
00118   exit(0);
00119  
00120 }
00121