d1cor

sock_inet_cli1.c

Oct 6th, 2016
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1. /*******************************************
  2. * Author     : Diego Cordoba / @d1cor      *
  3. * Purpose    : Junco TIC                   *
  4. * Contact    : juncotic.com                *
  5. *******************************************/
  6.  
  7. #include<stdio.h>
  8. #include<stdlib.h>
  9. #include<sys/types.h>
  10. #include<sys/stat.h>
  11. #include<unistd.h>
  12. #include<string.h>
  13. #include<fcntl.h>
  14. #include<errno.h>
  15. #include<netinet/in.h>
  16. #include<sys/socket.h>
  17.  
  18. #define BUF_SIZE 512
  19.  
  20. int main(int argc, char** argv) {
  21.  
  22.     char *error;
  23.     struct sockaddr_in dir;
  24.     int sockid,count;
  25.     char buffer[BUF_SIZE];
  26.    
  27.     //creamos el socket:
  28.     if((sockid=socket(PF_INET,SOCK_DGRAM,0))<0){
  29.         error="socket";
  30.         goto err;
  31.     }
  32.  
  33. /*
  34. struct sockaddr_in {
  35.     short            sin_family;   // e.g. AF_INET
  36.     unsigned short   sin_port;     // e.g. htons(3490)
  37.     struct in_addr   sin_addr;     // see struct in_addr, below
  38.     char             sin_zero[8];  // zero this if you want to
  39. };
  40.  
  41. struct in_addr {
  42.     unsigned long s_addr;  // load with inet_aton()
  43. };
  44. */
  45.  
  46.     dir.sin_family=AF_INET;
  47.     dir.sin_port = htons(1234);
  48.     dir.sin_addr.s_addr=inet_addr(*(argv+1));
  49.  
  50.     //enviamos los datos
  51.     //  count=sprintf(buffer,"hola mundo");
  52.  
  53.     while(count=read(STDIN_FILENO,buffer,BUF_SIZE)){
  54.         *(buffer+count)='\0'; // importante para la comparacion
  55.         if((sendto(sockid, buffer, count+1,0, (struct sockaddr *)&dir, sizeof(dir)))<0){
  56.             error="sendto";
  57.             goto err;
  58.         }
  59.         printf("Enviado...(%s - %d)\n",buffer,count);
  60.         if(!strcmp(buffer,"exit\n")){
  61.             printf("Saliendo del cliente...\n");
  62.             break;
  63.         }
  64.     }
  65.  
  66.     close(sockid);
  67.  
  68.     return 0;
  69. err:
  70.     fprintf(stderr,"%s %d %s\n",error,errno,strerror(errno));
  71. }
Add Comment
Please, Sign In to add comment