Advertisement
lutaco

Untitled

Jul 5th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <sys/time.h>
  4. #include <stdio.h>
  5. #include <netinet/in.h>
  6. #include <arpa/inet.h>
  7. #include <unistd.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <netdb.h>
  12. #include <memory.h>
  13.  
  14. // #define BUF_SIZE 64
  15. // int main()
  16. // {
  17. // int sock;
  18. // struct sockaddr_in addr;
  19. // char buf;
  20. // int bytes_read;
  21.  
  22. // sock = socket(AF_INET, SOCK_DGRAM, 0);
  23.  
  24. // addr.sin_family = AF_INET;
  25. // addr.sin_port = htons(3495);
  26. // addr.sin_addr.s_addr = htonl(INADDR_ANY);
  27. // bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0;
  28. // printf("%s\n", "la");
  29. // while(1)
  30. // {
  31. // printf("%s\n", "la");
  32. // bytes_read = recv(sock, &buf, 1, 0);
  33. // printf("%s\n", "la");
  34. // printf("%c", buf);
  35. // printf("%s\n", "la");
  36. // if (bytes_read<=0) break;
  37. // }
  38. // close(sock);
  39. // return 0;
  40. // }
  41.  
  42.  
  43.  
  44. main()
  45. {
  46. int s, namelen, client_address_size;
  47. struct sockaddr_in client, server;
  48. char buf[32];
  49.  
  50. if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
  51. {
  52. exit(1);
  53. }
  54.  
  55.  
  56. server.sin_family = AF_INET; /* Server is in Internet Domain */
  57. server.sin_port = 0; /* Use any available port */
  58. server.sin_addr.s_addr = INADDR_ANY;/* Server's Internet Address */
  59.  
  60. if (bind(s, (struct sockaddr *)&server, sizeof(server)) < 0)
  61. {
  62. exit(2);
  63. }
  64. /* Find out what port was really assigned and print it */
  65. namelen = sizeof(server);
  66. if (getsockname(s, (struct sockaddr *) &server, &namelen) < 0)
  67. {
  68. exit(3);
  69. }
  70.  
  71. printf("Port assigned is %d\n", ntohs(server.sin_port));
  72.  
  73. client_address_size = sizeof(client);
  74.  
  75. if(recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *) &client,
  76. &client_address_size) <0)
  77. {
  78. exit(4);
  79. }
  80.  
  81. printf("Received message %s from domain %s port %d internet\
  82. address %s\n",
  83. buf,
  84. (client.sin_family == AF_INET?"AF_INET":"UNKNOWN"),
  85. ntohs(client.sin_port),
  86. inet_ntoa(client.sin_addr));
  87.  
  88. close(s);
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement