我需要把像http://localhost/index.html这样的url中的所有超文本标记语言文本读入C语言的字符串中。
我知道如果我放在telnet -> telnet www.google.com 80 Get webpage....上,它会返回所有的html。
如何在linux环境中用C实现这一点?
发布于 2010-05-05 06:42:56
我建议使用几个库,这些库通常可以在大多数Linux发行版上使用:
libcurl和libxml2
libcurl提供了一套全面的http特性,而libxml2提供了一个名为HTMLParser的模块来解析html。
希望它能为你指明正确的方向
发布于 2010-05-05 06:41:22
下面是代码的大致轮廓(即,没有太多的错误检查,我也没有尝试编译它),以开始使用http://www.tenouk.com/cnlinuxsockettutorials.html来学习套接字编程。如果您需要将主机名(如google.com)转换为IP地址,请查找gethostbyname。此外,您可能需要做一些工作,从HTTP响应中解析出内容长度,然后确保不断调用recv,直到获得所有字节。
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <stdlib.h>
void getWebpage(char *buffer, int bufsize, char *ipaddress)
{
int sockfd;
struct sockaddr_in destAddr;
if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1){
fprintf(stderr, "Error opening client socket\n");
close(sockfd);
return;
}
destAddr.sin_family = PF_INET;
destAddr.sin_port = htons(80); // HTTP port is 80
destAddr.sin_addr.s_addr = inet_addr(ipaddress); // Get int representation of IP
memset(&(destAddr.sin_zero), 0, 8);
if(connect(sockfd, (struct sockaddr *)&destAddr, sizeof(struct sockaddr)) == -1){
fprintf(stderr, "Error with client connecting to server\n");
close(sockfd);
return;
}
// Send http request
char *httprequest = "GET / HTTP/1.0";
send(sockfd, httprequest, strlen(httprequest), 0);
recv(sockfd, buffer, bufsize, 0);
// Now buffer has the HTTP response which includes the webpage. You can either
// trim off the HTTP header, or just leave it in depending on what you are doing
// with the page
}发布于 2010-05-05 06:25:46
你使用套接字,用超文本传输协议询问网络服务器(你有"http://localhost/index.html"),然后解析你收到的数据。
如果您是套接字编程的初学者,这将非常有用:http://beej.us/guide/bgnet/
https://stackoverflow.com/questions/2769356
复制相似问题