c - 使用winsock下载文件不完整

时间:2014-11-10 04:15:30

标签: c windows

我有一个代码可以下载我网站的 .exe ,但问题是只下载 1kb 而且我不知道原因。也许是标题,但我不确定

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h> 
#include <string.h>
#include <winsock2.h>
#include <windows.h>

#define LEN_BUFF 400
#define CHUNK_SIZE 3000

int main() {    
    SOCKET fd;
    WSADATA wsaData;
    struct hostent *server;
    unsigned long addr = 0;

    struct sockaddr_in client;
    char Buffer[LEN_BUFF];

    if(WSAStartup(MAKEWORD(2,2),&wsaData) != 0) {
        printf("Error al iniciar el socket: %d",WSAGetLastError());
        getchar();
        return 1;
    }

    client.sin_family = AF_INET;
    client.sin_addr.s_addr = INADDR_ANY;
    client.sin_port = htons(80);
    server = gethostbyname("185.28.21.141");

    if(server == NULL) {
        printf("Server desconocido\n");
        getchar();
        return 1;
    }

    memcpy((char *) &client.sin_addr, server->h_addr, server->h_length);

    if((fd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("Error al iniciar socket\n");
        getchar();
        return 1;
    }

    if(connect(fd, (struct sockaddr *) &client, sizeof(client)) < 0) {
        printf("Error en connect()\n");
        getchar();
        return 1;
    }

    sprintf(Buffer, "GET %s HTTP/1.1\r\n\r\n", "/archivo/cliente_to_linux.exe");
    send(fd, Buffer, strlen(Buffer), 0);

    char buf[CHUNK_SIZE];
    int recv_size;
    FILE *fp = fopen("cliente_to_linux.exe", "wb");
    while((recv_size = recv(fd, buf, CHUNK_SIZE, 0)) > 0) {
        fwrite(buf, sizeof(char), recv_size, fp);
    }
    fclose(fp);

    printf("Archivo descargado con exito...\n");
    getchar();
    closesocket(fd);
    WSACleanup();

    return 0;
}

我的代码有什么问题?为什么只下载1kb?

0 个答案:

没有答案