zoukankan      html  css  js  c++  java
  • C语言:socket简单模拟http请求

    #include <stdio.h>
    #include <stdlib.h>
    
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    
    #include <netdb.h>
    
    #include <sys/types.h>
    
    #include <string.h>
    
    char *http_header = "GET / HTTP/1.1
    "
                                            "Host: www.idoushuo.com
    "
                                            "Connection: keep-alive
    i"
                                            "Accept: */*
    "
                                            "Connection: close
    "
                                            "
    ";
    
    char *hostname = "www.idoushuo.com";
    
    int main(){
            struct sockaddr_in addr;
            memset(&addr, 0, sizeof(addr));
            addr.sin_family = AF_INET;
            addr.sin_port = htons(80);
    
            struct hostent *hp;
            hp = gethostbyname(hostname);
            memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
    
            int sockfd = socket(AF_INET, SOCK_STREAM, 0);
            int ret = connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));
    
            //send
            send(sockfd, http_header, strlen(http_header), 0);
            //recv
            ssize_t length = 0;
            char buf[101];
            memset(buf, 0, sizeof(buf));
            char *response = calloc(1, sizeof(char));
            do{
                    length = recv(sockfd, buf, 100, 0);
                    if(length){
                            //leak mem
                            char *pp = realloc(response, strlen(response)+length+1);
                            if(!pp){
                                    break;
                            }
                            response = pp;
                            memcpy(response + strlen(response), buf, length);
                            memset(buf, 0x0, sizeof(buf));
                    }
            }while(length != 0);
    
            printf("%s
    ", response);
    
            free(response);
    }
  • 相关阅读:
    图形合并
    启动脚本
    图形合并
    :(){:|:&};:
    C言语教程第八章:列举,位运算(5)
    C言语图形情势编程,赋性鼠标(4)
    C言语教程第十章:文件(6)
    C言语教程第十章:文件(4)
    红帽为什么要连结桌面Linux
    阶乘较劲争论器改善版
  • 原文地址:https://www.cnblogs.com/bai-jimmy/p/5421007.html
Copyright © 2011-2022 走看看