我必须用 C 语言编写一个连接到服务器的 SSL 客户端,并获取 html 或文件。我设法获取了 html,但无法下载二进制文件。例如,我正在尝试从https://www.openssl.org/source/openssl-1.0.0d.tar.gz下载一个3.8mb的文件。我的代码只能下载其中的 1.1mb,而且我什至不知道我是否获得了正确的数据。
这是我为其制作的功能:
char *sslReadfile (connection *c)
{
const int readSize = 1024;
char *rc = NULL;
int received, count = 0;
char buffer[1024];
char filename[40];
printf("Input the file name to be saved:\n");
scanf("%s",filename);
FILE *fp;
fp = fopen(filename, "wb");
if (c)
{
while (1)
{
if (!rc)
rc = malloc (readSize * sizeof (char) + 1);
else
rc = realloc (rc, readSize * sizeof (char) + 1);
received = SSL_read (c->sslHandle, buffer, readSize);
buffer[received] = '\0';
if (received > 0)
fprintf(fp,"%s",buffer);//strcat (rc, buffer);
if (received < readSize)
break;
//count++;
}
}
printf("\nFile saved!! %s !!!\n\n",filename);
fclose(fp);
return rc;
}
哦,我这样调用它:
char command[50];
sprintf(command,"GET /%s\r\n\r\n",relativepath);
sslWrite (c, command);
response = sslReadfile (c);
其中 c 是我的连接。
最佳答案
不要使用fprintf
写入二进制数据。使用fwrite
。输出较小的原因是 fprintf
在第一个空字符处停止,跳过 1024 字节缓冲区中剩余的任何字符。另外,您似乎没有使用,也不需要 malloc
d rc
缓冲区。
因此,在调用 SSL_read
之后,您需要如下所示的内容:
if (received <= 0) break;
fwrite(buffer, 1, received, fp);
关于c - C中通过SSL下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6112123/