Advertisement
Guest User

Untitled

a guest
Jan 26th, 2015
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. /**
  2. * Simple echo server
  3. *
  4. * This program listens for connections on the
  5. * loopback interface, on port 9999. Upon connecting,
  6. * The first line we read, of up to BUF_LEN bytes, is
  7. * then sent back to the sender, and the connection
  8. * is closed.
  9. */
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <unistd.h>
  14. #include <errno.h>
  15. #include <sys/types.h>
  16. #include <sys/socket.h>
  17. #include <netinet/in.h>
  18.  
  19. #define BUF_LEN 25
  20. static char buf[BUF_LEN + 1];
  21.  
  22. int main(int argc, char *argv[])
  23. {
  24. int fd, c_fd = 0, i = 1;
  25. unsigned int bytes_read = 0;
  26. struct sockaddr_in sa;
  27.  
  28. /* Open a TCP socket */
  29. if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
  30. perror("socket");
  31. goto done;
  32. }
  33.  
  34. /* Let's ensure we can reuse our address */
  35. setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(int));
  36.  
  37. /* This will bind to localhost:9999 */
  38. memset(&sa, 0, sizeof(sa));
  39. sa.sin_family = AF_INET;
  40. sa.sin_port = htons(9999);
  41. sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  42.  
  43. if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
  44. perror("bind");
  45. goto done;
  46. }
  47.  
  48. /* Listen for one connection at a time */
  49. if (listen(fd, 1) < 0) {
  50. perror("listen");
  51. goto done;
  52. }
  53.  
  54. loop:
  55. /* Initialize our state variables and wait for connections */
  56. bytes_read = 0;
  57. memset(buf, 0, BUF_LEN+1);
  58.  
  59. if ((c_fd = accept(fd, NULL, NULL)) < 0) {
  60. perror("accept");
  61. goto loop;
  62. }
  63.  
  64. /* We've got a live one. */
  65. printf("Got connection\n");
  66.  
  67. /**
  68. * Read data until the buffer is full, we get an EOF, or
  69. * we've read a '\n'.
  70. */
  71. readit:
  72. if ((i = recv(c_fd, buf + bytes_read, BUF_LEN - bytes_read, 0)) > 0) {
  73. bytes_read += i;
  74. if (bytes_read < BUF_LEN && !strchr(buf, '\n'))
  75. goto readit;
  76. }
  77.  
  78. if (i < 0) {
  79. if (errno == EINTR)
  80. goto readit;
  81. perror("recv");
  82. goto next;
  83. }
  84.  
  85. /* Echo data if we got it */
  86. if (bytes_read) {
  87. buf[bytes_read + 1] = 0;
  88. printf("Read: %s\n", buf);
  89.  
  90. if (send(c_fd, buf, bytes_read, 0) < 0)
  91. perror("send");
  92. }
  93.  
  94. /* Kill this one, and wait for the next victim... */
  95. next:
  96. close(c_fd);
  97. goto loop;
  98.  
  99. done:
  100. if (c_fd) close(c_fd);
  101. close(fd);
  102. return EXIT_SUCCESS;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement