You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

73 lines
1.8 KiB

  1. #include <arpa/inet.h>
  2. #include <netdb.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <sys/socket.h>
  7. #include <sys/types.h>
  8. #define BACKLOG 10
  9. int main(int argc, char **argv) {
  10. int status;
  11. struct addrinfo hints;
  12. struct addrinfo *servinfo;
  13. struct sockaddr_storage their_addr;
  14. socklen_t addr_size;
  15. memset(&hints, 0, sizeof hints);
  16. hints.ai_family = AF_UNSPEC;
  17. hints.ai_socktype = SOCK_STREAM;
  18. hints.ai_flags = AI_PASSIVE;
  19. if ((status = getaddrinfo(NULL, "3490", &hints, &servinfo)) != 0) {
  20. fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
  21. exit(1);
  22. }
  23. int s;
  24. if ((s = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1) {
  25. fprintf(stderr, "socket error: %d\n", status);
  26. exit(1);
  27. }
  28. printf("%d\n", s);
  29. int yes=1;
  30. if ((status = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes)) == -1) {
  31. fprintf(stderr, "setsockopt error: %d\n", status);
  32. exit(1);
  33. }
  34. if((status = bind(s, servinfo->ai_addr, servinfo->ai_addrlen)) == -1) {
  35. fprintf(stderr, "bind error: %d\n", status);
  36. exit(1);
  37. }
  38. listen(s, BACKLOG);
  39. addr_size = sizeof their_addr;
  40. int new_fd = accept(s, (struct sockaddr *)&their_addr, &addr_size);
  41. printf("%d\n", new_fd);
  42. int t = 10;
  43. char c;
  44. while (t--) {
  45. char *msg = "Hi mom!\0";
  46. int len = strlen(msg), bytes_sent;
  47. if ((bytes_sent = send(new_fd, msg, len, 0)) == -1) {
  48. fprintf(stderr, "send error: %d\n", status);
  49. exit(1);
  50. }
  51. }
  52. char *msg = "Ja!\0";
  53. int len = strlen(msg), bytes_sent;
  54. if ((bytes_sent = send(new_fd, msg, len, 0)) == -1) {
  55. fprintf(stderr, "send error: %d\n", status);
  56. exit(1);
  57. }
  58. freeaddrinfo(servinfo);
  59. }