Advertisement
d1cor

sock_inet_dgram_srv.c

Oct 11th, 2017
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.89 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. /*
  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=htonl(INADDR_ANY); // 0.0.0.0
  49.         //estaria levantando el server en udp:0.0.0.0:1234
  50.  
  51.     /*
  52.         htons - host to network (short 16b)
  53.         htonl - host to network (long 32b)
  54.         ntohs ntohl - network to host short/long
  55.         ENDIAN:
  56.             big-endian (inversa)        host
  57.             litle-endian (correcta)     network
  58.     */
  59.  
  60.     //asociamos la direccion con el socket
  61.     if((bind(sockid, (struct sockaddr *)&dir,sizeof(dir)))<0){
  62.         error="bind";
  63.         goto err;
  64.     }
  65.    
  66.     while(count=recv(sockid,buffer,BUF_SIZE,0)){
  67.         if(count<0){
  68.             error="recv";
  69.             goto err;
  70.         }
  71.  
  72.         if(!strcmp(buffer,"exit\n")){
  73.             printf("Terminando servidor...\n");
  74.             break;
  75.         }
  76.  
  77.         printf("Recibiendo datos: %s",buffer);
  78.     }
  79.  
  80.     close(sockid);
  81.  
  82.     return 0;
  83. err:
  84.     fprintf(stderr,"%s %d %s\n",error,errno,strerror(errno));
  85. }
  86.  
  87. // https://tmate.io/t/ro-bxSy6AiKE6wKjHoDHJ6WOjXft
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement