Advertisement
danielhilst

hwtcp.c

Apr 12th, 2014
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.16 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <netinet/in.h>
  7.  
  8.  
  9. #define STR "Hello tcp world\n"        
  10. #define pexit(x)                                \
  11.         do {                                    \
  12.                 perror(x);                      \
  13.                 exit(EXIT_FAILURE);             \
  14.         } while (0)
  15.  
  16.  
  17. static struct sockaddr_in saddr;
  18.  
  19. int main(void)
  20. {
  21.         int sock, clisock;
  22.         int len = strlen(STR);
  23.  
  24.         sock = socket(AF_INET, SOCK_STREAM, 0);
  25.        
  26.         saddr.sin_family = AF_INET;
  27.         saddr.sin_addr.s_addr = htonl(INADDR_ANY);
  28.         saddr.sin_port = htons(80);
  29.  
  30.         if (bind(sock, (struct sockaddr *)&saddr, sizeof(saddr)))
  31.                 pexit("bind");
  32.  
  33.         if (listen(sock, 10))
  34.                 pexit("listen");
  35.  
  36.         for (;;) {
  37.  
  38.                 if ((clisock = accept(sock, NULL, NULL)) == -1) {
  39.                         perror("accept");
  40.                         continue;
  41.                 }
  42.  
  43.                 if (send(clisock, STR, len, 0) != len)
  44.                         perror("send");
  45.  
  46.                 close(clisock);
  47.         }
  48.  
  49.         return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement