client.c

Go to the documentation of this file.
00001 #include <sys/types.h>
00002 #include <sys/socket.h>
00003 #include <sys/stat.h>
00004 #include <netinet/in.h>
00005 #include <netdb.h>
00006 #include <stdio.h>
00007 #include <string.h>
00008 
00009 #define TAMMSG 80
00010 
00011 int main(int argc, char *argv[])
00012 {
00013 
00014   int s1;
00015 
00016   struct sockaddr_in server;
00017   struct hostent *hp, *gethostbyname();
00018 
00019   char msg[TAMMSG] ;
00020 
00021   if (argc < 3) {
00022      printf("Erro uso correto:\n") ;
00023      printf("\n    %s <hostname> <portnumber>\n\n", argv[0]) ;
00024      exit(1) ;
00025   }
00026     
00027   s1=socket(AF_INET, SOCK_STREAM, 0);
00028 
00029   if (s1<0) {
00030      perror("opening stream socket");
00031      exit(1);
00032   }
00033 
00034   hp = gethostbyname(argv[1]);
00035   if (hp == 0) {
00036      fprintf(stderr,"%s: Unkown host\n",argv[1]);
00037      exit(2);
00038   }
00039   
00040   server.sin_family = AF_INET;
00041   server.sin_port = htons(atoi(argv[2]));
00042   server.sin_addr = *((struct in_addr *)hp->h_addr);
00043   memset(&(server.sin_zero), '\0', 8);  // zero the rest of the struct 
00044     
00045 
00046   if (connect(s1, (struct sockaddr *)&server, sizeof server ) < 0) {
00047     perror("connectando stream socket");
00048     exit(1);
00049   }
00050 
00051   printf("\nTalk>") ;
00052   
00053   do {
00054          scanf("%s", &msg);
00055          printf("Enviei: %s\n",msg);
00056          sprintf(msg,"%s\n",msg);
00057                  send(s1, msg, strlen(msg), 0);
00058   }while(msg[0] != '.'); 
00059   
00060   close(s1);
00061   exit(0);
00062  
00063 }