资源简介
linux下C/C++实现已知url通过socket访问网页并获得网页文字内容
代码片段和文件信息
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define PORT 80
#define BUFSIZE 4092
int main(int argc char *argv[])
{
FILE * fp;
int sockfd;
int ret;
int i;
int h;
struct hostent * host;
struct sockaddr_in servaddr;
char str1[4096];
char buf[BUFSIZE];
char *str;
socklen_t len;
fd_set t_set1;
struct timeval tv;
host = gethostbyname(argv[1]);
fp = fopen(“/root/writeurl.txt““a“);
if(fp < 0)
{
printf(“open file fail...\n“);
return -1;
}
if ((sockfd = socket(AF_INET SOCK_STREAM 0)) < 0 )
{
printf(“socket error!\n“);
exit(0);
};
bzero(&servaddr sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr = *((struct in_addr*)host->h_addr);
if (connect(sockfd (struct sockaddr *)&servaddr sizeof(servaddr)) < 0)
{
printf(“connect error!\n“);
exit(0);
}
printf(“connect success \n“);
memset(str1 0 4096);
sprintf(str1“GET / HTTP/1.0\r\nHost:%s\r\nContent-Type=text/plain\r\nConnection:Close\r\n\r\n“argv[1]);
ret = send(sockfd(void *)str1strlen(str1)0);
if (ret < 0)
{
printf(“send error %d,Error message‘%s‘\n“errno strerror(errno));
exit(0);
}
else
{
printf(“send success total send %d \n“ ret);
}
while(1)
{
tv.tv_sec= 0;
tv.tv_usec= 0;
h= 0;
FD_ZERO(&t_set1);
FD_SET(sockfd &t_set1);
h= select(sockfd +1 &t_set1 NULL NULL &tv);
if (h == 0) continue;
if (h < 0)
{
close(sockfd);
printf(“some thing read error!\n“);
return -1;
};
if (h > 0)
{
memset(buf 0 4095);
i= recv(sockfd (void *)buf 40920);
if (i==0)
{
close(sockfd);
printf(“read message find stop!\n“);
return -1;
}
fwrite(buf1ifp);
printf(“%s\n“ buf);
}
}
fclose(fp);
close(sockfd);
return 0;
}
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 2098 2013-04-07 16:16 第二题\url.c
目录 0 2013-04-10 14:41 第二题
----------- --------- ---------- ----- ----
2098 2
- 上一篇:mfc读取excel
- 下一篇:8605 删数问题
评论
共有 条评论