zoukankan      html  css  js  c++  java
  • linux利用socket编程来下载网页的html代码

    linux利用socket编程来下载网页的html代码
    2009-05-20 14:53
    编译该程序: gcc -g wclient.c -o wclient
    运行该程序: ./wclient www.baidu.com 80
    抓取百度首页的html代码

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <stdarg.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netdb.h>

    //建立一个http tcp 连接的辅助函数
    int htconnect(char *domain, int port)
    {
    int white_sock;
    struct hostent *site;
    struct sockaddr_in me;

    //获得服务器的名称
    site = gethostbyname(domain);
    if(NULL == site)
    {
        return (-2);
    }
    //建立套接字
    white_sock = socket(AF_INET, SOCK_STREAM, 0);
    if(white_sock < 0)
    {
        return (-1);
    }
    //初始化为0
    memset(&me, 0, sizeof(struct sockaddr_in));
    memcpy(&me.sin_addr, site->h_addr_list[0], site->h_length);
    me.sin_family = AF_INET;
    me.sin_port = htons(port);

    //建立连接
    return ( (connect(white_sock, (struct sockaddr*)&me, sizeof(struct sockaddr))<0)?1:white_sock ); 
    }

    void main(int argc, char** argv)
    {
    int black_sock;
    char bugs_bunny[3];
    if(argc < 2)
    {
        printf("usage:\nwClient host\n");
        return;
    }
    black_sock = htconnect(argv[1], 80);

    if (black_sock<0)
    {
           printf ( "Socket Connect Error!\n") ;
           return ;
    }

    char *msg = "GET / HTTP/1.1\r\n\r\n";
    if( send(black_sock, msg, strlen(msg), 0)<0 )
    {
       perror("error in send msg\n");
       exit(1);
    }

    char buf[1000];
    while(1)
    {
       while((recv(black_sock,buf,1000,MSG_WAITALL))>0)
       {
       printf("%s",buf);
       }
    }
    close(black_sock);
    }
  • 相关阅读:
    linux下创建一个指定大小的文件
    批量替换多个文件中的字符串
    redhat 搭建yum 源
    python ConfigParser 模块
    python yaml 模块
    python xml文件处理
    py2exe 和pyinstaller打包
    wxpython 学习之 --threading
    wxpython 学习之 --文本框与Boxsizer布局管理器
    wxpython 学习之 --窗口分割
  • 原文地址:https://www.cnblogs.com/lexus/p/2248979.html
Copyright © 2011-2022 走看看