Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1.  
  2. // Server side implementation of UDP client-server model
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <string.h>
  7. #include <sys/types.h>
  8. #include <sys/socket.h>
  9. #include <arpa/inet.h>
  10. #include <netinet/in.h>
  11.  
  12. #define PORT 10101
  13. #define MAXLINE 1024
  14.  
  15. // Driver code
  16. int main() {
  17. int sockfd;
  18. char buffer[MAXLINE];
  19. char *hello = "Hello from server";
  20. struct sockaddr_in servaddr, cliaddr;
  21.  
  22. // Creating socket file descriptor
  23. if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
  24. perror("socket creation failed");
  25. exit(EXIT_FAILURE);
  26. }
  27.  
  28. memset(&servaddr, 0, sizeof(servaddr));
  29. memset(&cliaddr, 0, sizeof(cliaddr));
  30.  
  31. // Filling server information
  32. servaddr.sin_family = AF_INET; // IPv4
  33. servaddr.sin_addr.s_addr = INADDR_ANY;
  34. servaddr.sin_port = htons(PORT);
  35.  
  36. // Bind the socket with the server address
  37. if ( bind(sockfd, (const struct sockaddr *)&servaddr,
  38. sizeof(servaddr)) < 0 )
  39. {
  40. perror("bind failed");
  41. exit(EXIT_FAILURE);
  42. }
  43.  
  44. int len, n;
  45.  
  46. aaa:
  47. n = recvfrom(sockfd, (char *)buffer, MAXLINE,
  48. MSG_WAITALL, ( struct sockaddr *) &cliaddr,
  49. &len);
  50. buffer[n] = '\0';
  51. printf("Client : %s\n", buffer);
  52. //sendto(sockfd, (const char *)hello, strlen(hello),
  53. // MSG_CONFIRM, (const struct sockaddr *) &cliaddr,
  54. // len);
  55. printf("Hello message sent.\n");
  56.  
  57. goto aaa;
  58.  
  59. return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement