Advertisement
d1cor

sock_inet_dgram_cli.c

Oct 11th, 2017
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.23 KB | None | 0 0
  1. /*******************************************
  2. * Author     : Diego Cordoba / @d1cor      *
  3. * Contact    : juncotic.com - um.edu.ar    *
  4. *******************************************/
  5.  
  6. #include<stdio.h>
  7. #include<stdlib.h>
  8. #include<sys/types.h>
  9. #include<sys/stat.h>
  10. #include<unistd.h>
  11. #include<string.h>
  12. #include<fcntl.h>
  13. #include<errno.h>
  14. #include<netinet/in.h>
  15. #include<sys/socket.h>
  16. #include <arpa/inet.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.     dir.sin_family=AF_INET;
  34.     dir.sin_port = htons(1234);
  35.     dir.sin_addr.s_addr=inet_addr(*(argv+1));
  36.  
  37.     while(count=read(STDIN_FILENO,buffer,BUF_SIZE)){
  38.         *(buffer+count)='\0'; // importante para la comparacion
  39.         if((sendto(sockid, buffer, count+1,0, (struct sockaddr *)&dir, sizeof(dir)))<0){
  40.             error="sendto";
  41.             goto err;
  42.         }
  43.         printf("Enviado...(%s - %d)\n",buffer,count);
  44.         if(!strcmp(buffer,"exit\n")){
  45.             printf("Saliendo del cliente...\n");
  46.             break;
  47.         }
  48.     }
  49.  
  50.     close(sockid);
  51.  
  52.     return 0;
  53. err:
  54.     fprintf(stderr,"%s %d %s\n",error,errno,strerror(errno));
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement