帮忙调试,一小段抓取网页的C程序!

LeonTown LeonTown 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
从网上抄的一段代码,
用于抓取指定的网页。
代码如下:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//#ifndef _WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
//#endif

char* host = "www.baidu.com"; //指定为抓取www.baidu.com页面
int port = 80;

int main(void)
{
char buffer[4096];
int isock;
struct sockaddr_in pin;
struct hostent * remoteHost;
char message[512];
int done = 0;
int chars = 0;
int l = 0;

if( (remoteHost = gethostbyname(host)) == 0 )
{
printf("Error resolving host\n");
exit(1);
}

bzero(message,sizeof(message));
bzero(&pin,sizeof(pin));
pin.sin_family = AF_INET;
pin.sin_port = htons(port);
pin.sin_addr.s_addr = ( (struct in_addr *)(remoteHost->h_addr) )->s_addr;

if( (isock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("Error opening socket!\n");
exit(1);
}
sprintf(message, "GET / HTTP/1.1\r\n");
strcat(message, "Host:www.baidu.com\r\n");
strcat(message, "Accept: */*\r\n");
strcat(message, "User-Agent: Mozilla/4.0(compatible)\r\n");
strcat(message, "connection:Keep-Alive\r\n");
strcat(message, "\r\n\r\n");

printf("%s",message);

if( connect(isock, /*(void *)*/ (const sockaddr*)&pin, sizeof(pin)) == -1 )
{
printf("Error connecting to socket\n");
exit(1);
}

if( send(isock, message, strlen(message), 0) == -1)
{
printf("Error in send\n");
exit(1);
}

while(done == 0)
{
l = recv(isock, buffer, 1, 0);
if( l < 0 )
done = 1;
switch(*buffer)
{
case '\r':
break;
case '\n':
if(chars == 0)
done = 1;
chars = 0;
break;
default:
chars++;
break;
}
printf("%c",*buffer);
}

printf("begin to crawling page\n");

do
{
l = recv(isock, buffer, sizeof(buffer) - 1, 0);
if( l < 0 )
break;
*(buffer + l) = 0;
fputs(buffer, stdout);
}while( l > 0 );

// close(isock);
shutdown(isock, SHUT_RDWR);
return 0;
}


编译运行后,
程序在抓取一部分信息后,会“僵死”住。
希望大家能帮忙找出问题在哪里。

抓取其它的网页也是类似的“僵死”问题。

另外,curl命令还真是很牛逼,
不知道代码是怎么实现的。。。
...全文
评论 7
收藏 已收藏
分享
返回顶部
LeonTown
Linux/Unix社区 23,224 成员 74,535 内容