zoukankan      html  css  js  c++  java
  • Example: A simple blocking HTTP client

    /* For sockaddr_in */
    #include <netinet/in.h>
    /* For socket functions */
    #include <sys/socket.h>
    /* For gethostbyname */
    #include <netdb.h>
    
    #include <unistd.h>
    #include <string.h>
    #include <stdio.h>
    
    int main(int c, char **v)
    {
        const char query[] =
            "GET / HTTP/1.0\r\n"
            "Host: www.google.com\r\n"
            "\r\n";
        const char hostname[] = "www.google.com";
        struct sockaddr_in sin;
        struct hostent *h;
        const char *cp;
        int fd;
        ssize_t n_written, remaining;
        char buf[1024];
    
        /* Look up the IP address for the hostname.   Watch out; this isn't
           threadsafe on most platforms. */
        h = gethostbyname(hostname);
        if (!h) {
            fprintf(stderr, "Couldn't lookup %s: %s", hostname, hstrerror(h_errno));
            return 1;
        }
        if (h->h_addrtype != AF_INET) {
            fprintf(stderr, "No ipv6 support, sorry.");
            return 1;
        }
    
        /* Allocate a new socket */
        fd = socket(AF_INET, SOCK_STREAM, 0);
        if (fd < 0) {
            perror("socket");
            return 1;
        }
    
        /* Connect to the remote host. */
        sin.sin_family = AF_INET;
        sin.sin_port = htons(80);
        sin.sin_addr = *(struct in_addr*)h->h_addr;
        if (connect(fd, (struct sockaddr*) &sin, sizeof(sin))) {
            perror("connect");
            close(fd);
            return 1;
        }
    
        /* Write the query. */
        /* XXX Can send succeed partially? */
        cp = query;
        remaining = strlen(query);
        while (remaining) {
          n_written = send(fd, cp, remaining, 0);
          if (n_written <= 0) {
            perror("send");
            return 1;
          }
          remaining -= n_written;
          cp += n_written;
        }
    
        /* Get an answer back. */
        while (1) {
            ssize_t result = recv(fd, buf, sizeof(buf), 0);
            if (result == 0) {
                break;
            } else if (result < 0) {
                perror("recv");
                close(fd);
                return 1;
            }
            fwrite(buf, 1, result, stdout);
        }
    
        close(fd);
        return 0;
    }
  • 相关阅读:
    HDU1712:ACboy needs your help(分组背包模板)
    HDU1203:I NEED A OFFER!(01背包)
    HDU1171:Big Event in HDU
    POJ1014:Dividing(多重背包)
    HDU2191-悼念512汶川大地震遇难同胞——珍惜现在,感恩生活(多重背包入门)
    hdu2159FATE(二维背包)
    POJ1201 Intervals
    C++之运算符重载
    C++之强制类型转换
    MFC WinInetHttp抓取网页代码内容
  • 原文地址:https://www.cnblogs.com/UnGeek/p/2994530.html
Copyright © 2011-2022 走看看