简单的C HTTP GET

如下:

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */


int httpGet(char *host, int portno, char* file, char** response) {
    char *message_fmt = "GET /?file=%s HTTP/1.0\r\n\r\n";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total;
    char message[1024];
    int bufSize = 2048;
    *response = (char *)malloc(bufSize * sizeof(char));
    memset(*response, 0, bufSize);
   
    /* fill in the parameters */
    sprintf(message,message_fmt, file);
    printf("Request:\n%s\n",message);

    /* create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("ERROR opening socket"); return -1;
    }

    /* lookup the ip address */
    server = gethostbyname(host);
    if (server == NULL) {
        perror("ERROR, no such host"); return -1;
    }

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) {
        perror("ERROR connecting"); return -1;
    }

    /* send the request */
    total = strlen(message);
    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0) {
            perror("ERROR writing message to socket"); return -1;
        }
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);

    /* receive the response */
    total = bufSize - 1;
    received = 0;
    do {
        bytes = read(sockfd, (*response)+received, total-received);
        if (bytes < 0) {
            perror("ERROR reading response from socket"); return -1;
        }
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total) {
        perror("ERROR storing complete response from socket"); return -1;
    }

    /*close the socket */
    close(sockfd);
    return 0;
}


int main(int argc,char *argv[])
{
    /* first what are we going to send and where are we going to send it? */
    int portno =        8000;
    char *host =        "192.168.1.6";
    
    
    
    char *res;
    httpGet(host, portno, "GUANJI.1.wav", &res);
    printf("Response:\n%s\n", res);
    free(res);
    
    return 0;
}



评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×