Advertisement
Guest User

Untitled

a guest
Feb 19th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.32 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stdlib.h>
  4. #include<arpa/inet.h>
  5. #include<sys/socket.h>
  6.  
  7. #define BUFLEN 512
  8. #define PORT 8888
  9.  
  10.  
  11. int main(void)
  12. {
  13.         struct sockaddr_in si_me;
  14.         memset(&si_me, 0, sizeof(struct sockaddr_in));
  15.         si_me.sin_family = AF_INET;
  16.         si_me.sin_port = htons(PORT);
  17.         si_me.sin_addr.s_addr = htonl(INADDR_ANY);
  18.        
  19.        
  20.         struct sockaddr_in si_other;
  21.         int i = sizeof(si_other);
  22.         int slen = recv_len;
  23.         char buf[BUFLEN];
  24.  
  25.         //create a UDP socket
  26.         int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
  27.  
  28.         //bind socket to port
  29.         bind(s, (struct sockaddr*) &si_me, sizeof(si_me) )
  30.  
  31.         //keep listening for data
  32.         while(1)
  33.         {
  34.                 printf("Waiting for data...");
  35.                 fflush(stdout);
  36.                 recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)
  37.                
  38.                 printf("Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
  39.                 printf("Data: %s\n" , buf);
  40.                
  41.                 //now reply the client with the same data
  42.                 sendto(s, buf, recv_len, 0, (struct sockaddr*) &si_other, slen)
  43.         }
  44.  
  45.         close(s);
  46.         return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement