envio de archivo
Publicado por cris (1 intervención) el 15/11/2002 07:52:00
Quiero enviar un archivo utilizando c, debo utilizar el protocolo http (o algun otro), alguien puede ayudarme?
Valora esta pregunta


0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define BUFFER_SIZE 1024
void sendFile(const char *hostname, int port, const char *filepath) {
int sock;
struct sockaddr_in server_addr;
FILE *file;
char buffer[BUFFER_SIZE];
char *file_data;
long file_size;
// Abrir el archivo
file = fopen(filepath, "rb");
if (file == NULL) {
perror("Error al abrir el archivo");
return;
}
// Obtener el tamaño del archivo
fseek(file, 0, SEEK_END);
file_size = ftell(file);
fseek(file, 0, SEEK_SET);
// Crear el socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("Error al crear el socket");
fclose(file);
return;
}
// Configurar la dirección del servidor
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
inet_pton(AF_INET, hostname, &server_addr.sin_addr);
// Conectar al servidor
if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("Error al conectar al servidor");
close(sock);
fclose(file);
return;
}
// Preparar la solicitud HTTP POST
snprintf(buffer, sizeof(buffer),
"POST /upload HTTP/1.1\r\n"
"Host: %s\r\n"
"Content-Type: application/octet-stream\r\n"
"Content-Length: %ld\r\n"
"Connection: close\r\n"
"\r\n", hostname, file_size);
// Enviar la solicitud
send(sock, buffer, strlen(buffer), 0);
// Leer el archivo y enviarlo
file_data = (char *)malloc(file_size);
fread(file_data, 1, file_size, file);
send(sock, file_data, file_size, 0);
// Limpiar
free(file_data);
fclose(file);
close(sock);
printf("Archivo enviado con éxito.\n");
}
int main() {
const char *hostname = "127.0.0.1"; // Cambia esto por la dirección del servidor
int port = 8080; // Cambia esto por el puerto del servidor
const char *filepath = "ruta/al/archivo.txt"; // Cambia esto por la ruta del archivo
sendFile(hostname, port, filepath);
return 0;
}