tomasaccini

Untitled

Jul 18th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.60 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdint.h>
  5.  
  6. int aceptar_cliente(const char* port, const char* ip){
  7.     struct addrinfo* socketinfo;
  8.     getaddrinfo(ip, port, NULL, socketinfo);
  9.     // Asumo que el primer resultado es el vĂ¡lido.
  10.     int sock = socket(socketinfo->ai_family, socketinfo->ai_socktype, socketinfo->ai_protocol);
  11.     bind(sock, socketinfo->ai_addr, socketinfo->ai_addrlen);
  12.     freeaddrinfo(socketinfo);
  13.     listen(sock, 1);
  14.     return accept(sock);
  15. }
  16.  
  17. int recibir(int socket, char (*buf)[], size_t tamanio) {
  18.     size_t recibidos = 0;
  19.     int resultado = 0;
  20.     while (recibidos < tamanio) {
  21.         resultado = recv(socket, buf[recibidos], tamanio - recibidos);
  22.         if (resultado <= 0) return resultado;
  23.         recibidos += resultado;
  24.     }
  25.     return recibidos;
  26. }
  27.  
  28. uint32_t recibir_tamanio(int socket) {
  29.     char buf[4];
  30.     int resultado = recibir(socket, &buf, 4);
  31.     if (resultado <= 0) return -1;
  32.     uint32_t valor;
  33.     memcpy(&valor, buf, 4);
  34.     valor = ntohl(valor);
  35.     return valor;
  36. }
  37.  
  38.  
  39.  
  40. int main() {
  41.     int sock = aceptar_cliente(NULL, "3280");
  42.     int tamanio;
  43.     size_t numeracion = 1;
  44.     int resultado;
  45.     while ( (tamanio = recibir_tamanio(sock)) > 0 ) {
  46.         char buf[tamanio];
  47.         resultado = recibir(sock, &buf, tamanio);
  48.         if (resultado != tamanio) return -1;
  49.         char filename[sizeof("100.html")];
  50.         sprintf(filename, "%zu.html", numeracion);
  51.         FILE* f = fopen(filename, "w");
  52.         fwrite(buf, tamanio, 1, f);
  53.         fclose(f);
  54.         numeracion++;
  55.     }
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment