Advertisement
chronomantic

tcp_server

Dec 15th, 2019
498
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.59 KB | None | 0 0
  1. #include    <stdio.h>
  2. #include    <stdlib.h>
  3. #include    <string.h>
  4. #include    <sys/types.h>
  5. #include    <sys/socket.h>
  6. #include    <netinet/in.h>
  7. #include    <unistd.h>
  8.  
  9. #define BUFFER_SIZE 1024
  10. #define HEADER_SIZE 4
  11.  
  12.  
  13. void vuln_read(int cli_fd) {
  14.   char buffer[BUFFER_SIZE];
  15.  
  16.   // read 4 bytes to get how many bytes to read
  17.   // assuming that incoming header is in little endian
  18.   int to_read;
  19.   read(cli_fd, &to_read, HEADER_SIZE);
  20.   printf("Will read %d bytes\n", to_read);
  21.  
  22.   int read_bytes = read(cli_fd, buffer, to_read);
  23.   printf("Read: %d bytes\n", read_bytes);
  24.   printf("Incoming message: %s\n", buffer);
  25. }
  26.  
  27. int main (int argc, char **argv){
  28.   if (argc < 2) {
  29.     printf("Usage: %s [port]\n", argv[0]);
  30.     exit(1);
  31.   }
  32.  
  33.   int port, sock_fd, cli_fd;
  34.   socklen_t cli_len;
  35.   struct sockaddr_in serv_addr, cli_addr;
  36.  
  37.   sock_fd = socket(AF_INET, SOCK_STREAM, 0);
  38.   if (sock_fd < 0) {
  39.     printf("Error opening a socket\n");
  40.     exit(1);
  41.   }
  42.  
  43.   port = atoi(argv[1]);
  44.   serv_addr.sin_family = AF_INET;
  45.   serv_addr.sin_addr.s_addr = INADDR_ANY;
  46.   serv_addr.sin_port = htons(port);
  47.  
  48.   if (bind(sock_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
  49.     printf("Error on bind()\n");
  50.     exit(1);
  51.   }
  52.  
  53.   listen(sock_fd, 1);
  54.   cli_len = sizeof(cli_addr);
  55.   cli_fd = accept(sock_fd, (struct sockaddr *) &cli_addr, &cli_len);
  56.   if (cli_fd < 0) {
  57.     printf("Error on accept()\n");
  58.     exit(1);
  59.   }
  60.  
  61.   vuln_read(cli_fd);
  62.  
  63.   char message[] = "Hello there!\n";
  64.   write(cli_fd, message, strlen(message));
  65.  
  66.   close(cli_fd);
  67.   close(sock_fd);
  68.  
  69.   return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement