我试图使用c获得我的网站的源代码,我能够连接和一切,但当我实现recv()代码时,它只接收源代码的最后几个字节。我想动态地为缓冲区分配空间,以便使用C函数malloc
和realloc
接收更多。
这是我到目前为止的代码:
char *buffer = NULL;
unsigned int i = 0;
unsigned long LEN = 200;
unsigned long cur_size = 0;
buffer = (char*)malloc(sizeof(char)*LEN);
do
{
if( status >= LEN )
{
cur_size += status;
buffer = (char*)realloc(buffer, cur_size);
}
status = recv(cSocket, buffer, LEN, 0);
if( status == 0 )
{
printf("Byen");
}
else if( status > 0 )
{
printf("%dn", status);
}
else
{
printf("socket error=%dn", WSAGetLastError());
break;
}
}while( status > 0 );
printf("%sn", buffer);
它仍然不打印整个源代码。我该怎么做呢?
伪代码:
buffer = 'len chars';
loop:
if( status >= buffer ) buffer = 'resize to status chars';
status = recv(sock, buffer, len, 0);
end loop
当您提前调整缓冲区大小时,这需要通过其大小反映出来。当前是而不是。
要解决这个问题,您可以,例如,通过更改
将cur_size
初始化为LEN
unsigned long cur_size = 0;
unsigned long cur_size = LEN;
假设上面的修复,您希望附加到缓冲区,而不是每次调用recv()
都覆盖它。
改变这一行
status = recv(cSocket, buffer, LEN, 0);
status = recv(cSocket, buffer + cur_size - LEN, LEN, 0);
一种更直接的方法是不跟踪缓冲区的大小,而是跟踪接收到的字节数,并且总是以恒定的大小增加缓冲区。
分配内存的两个调用也可以用一个调用代替:
char *buffer = NULL;
unsigned long LEN = 200;
unsigned long bytes_received = 0;
unsigned long cur_size = 0;
int status = 0;
do
{
if (bytes_received >= cur_size)
{
char * tmp;
cur_size += LEN;
tmp = realloc(buffer, cur_size);
if (NULL == tmp)
{
fprintf(stderr, "realloc error=%dn", WSAGetLastError());
break;
}
buffer = tmp;
}
status = recv(cSocket, buffer + bytes_received, LEN, 0);
if (status == 0)
{
printf("Byen");
}
else if (status > 0)
{
bytes_received += status;
printf("%dn", status);
}
else /* < 0 */
{
fprintf(stderr, "socket error=%dn", WSAGetLastError());
}
} while (status > 0);
printf("%sn", buffer);
嗯,经过一番研究,我偶然发现了这个网站,终于找到了我要找的东西。
二进制潮汐虽然它使用linux的fcntl
,但windows的等效ioctlsocket
用于设置套接字的非阻塞模式。
要查看确切的功能,请访问网站。我修改了版本并将我的套接字设置为阻塞模式。
int total_recv(SOCKET s)
{
int size_recv = 0, total_size = 0, block = 00;
char chunk[BUFLEN];
ioctlsocket(s, FIONBIO, (unsigned long*)&block); // set mode to block
// not necessary but clarification of function, mode is block by
// default
while( 1 )
{
memset(chunk, 0, BUFLEN);
if( ( size_recv = recv(s, chunk, BUFLEN, 0) ) == SOCKET_ERROR )
{
printf("Error receivingn");
}
else if( size_recv == 0 )
{
break;
}
else
{
total_size += size_recv;
// i used file since console wouldn't show full source code
FILE *fp = NULL;
fp = fopen("source.txt", "a");
fprintf(fp, chunk);
fclose(fp);
}
}
return total_size;
}