首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Linux C++调用网页

问从Linux C++调用网页
EN

Stack Overflow用户
提问于 2010-05-05 06:21:47
回答 5查看 2.4K关注 0票数 2

我需要把像http://localhost/index.html这样的url中的所有超文本标记语言文本读入C语言的字符串中。

我知道如果我放在telnet -> telnet www.google.com 80 Get webpage....上,它会返回所有的html。

如何在linux环境中用C实现这一点?

EN

回答 5

Stack Overflow用户

发布于 2010-05-05 06:42:56

我建议使用几个库,这些库通常可以在大多数Linux发行版上使用:

libcurl和libxml2

libcurl提供了一套全面的http特性,而libxml2提供了一个名为HTMLParser的模块来解析html。

希望它能为你指明正确的方向

票数 6
EN

Stack Overflow用户

发布于 2010-05-05 06:41:22

下面是代码的大致轮廓(即,没有太多的错误检查,我也没有尝试编译它),以开始使用http://www.tenouk.com/cnlinuxsockettutorials.html来学习套接字编程。如果您需要将主机名(如google.com)转换为IP地址,请查找gethostbyname。此外,您可能需要做一些工作,从HTTP响应中解析出内容长度,然后确保不断调用recv,直到获得所有字节。

代码语言:javascript
复制
#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
}
票数 3
EN

Stack Overflow用户

发布于 2010-05-05 06:25:46

你使用套接字,用超文本传输协议询问网络服务器(你有"http://localhost/index.html"),然后解析你收到的数据。

如果您是套接字编程的初学者,这将非常有用:http://beej.us/guide/bgnet/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2769356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档