日期:2014-05-16  浏览次数:20522 次

简单的linux -c http-client
#include<stdio.h>
#include <unistd.h>
#include<fcntl.h>
#include<netdb.h>
#include<stdlib.h>
#include "httpclient.h"
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include <netinet/in.h>

const char * http_s = "http://";

typedef struct{

char *url;
int port;
char *host;
char *anyurl;
int isip;

}Hostinfo;

int isip(const char * s){

         while( *s ){
                 if(isalpha(*s) && *s != '.')
                  {
                         return 0;
                  }     
                  s++;  
         }       
        
         return 1;
        
}

int gethostinfobyurl(const char * url, char ** host, int *port, char ** anyurl)
{

if(url == NULL || 0!=strncmp(url, http_s, strlen(http_s)) ){

printf("url is not legal, %s\n", url);

return -1;
}


char * h_url = strstr(url,"//");

h_url = h_url + 2;

*anyurl= strchr(h_url,'/');

printf("hurl: %s\n",h_url);
if(anyurl != NULL){

char cc[1024];
char *pcc = cc;
strcpy(cc,h_url);
h_url = strsep(&pcc,"/");
printf("hhurl:%s\n",h_url);
}

if(NULL !=strchr(h_url,':')){

*host = strsep(&h_url,":");
char *cport = strsep(&h_url,":");
*port = atoi(cport);
}
else{

*host = h_url;
}
return 0;
}

void datas(int fp,Hostinfo *hinfo){

char request[1024];
bzero(&request,1024);
//sprintf(request,"GET %s  HTTP/1.1\r\nHost:  61.135.169.125:80\r\nConnection:   Close\r\n\r\n","/");
sprintf(request,   "GET   %s   HTTP/1.1\r\nAccept:   */*\r\nAccept-Language:   zh-cn\r\n\
Host:  %s:%d\r\nConnection:   Close\r\n\r\n ", hinfo->anyurl,hinfo->host,hinfo->port);

printf("\n\n");
printf("%s",request);

printf("\n\n");

printf("request is %s\n", request);
int send = write(fp, request,strlen(request));

if(send == -1){

printf("send error\n");
exit(1);
}


printf("send num: %d\n", send);
int BUFFER_SIZE = 2048;
char buffer[BUFFER_SIZE];
int length;
bzero(&buffer, BUFFER_SIZE);

        length = read(fp,buffer,BUFFER_SIZE);
char * content = buffer;


if(length <=0){

printf("error! read http return content!");

//return NULL;
}
char * head = strsep(&content,"\r\n");
printf("head:%s\n",head);

strsep(&head," ");

printf("1-->>head:%s\n",head);
if(head == NULL){


printf("error! read http return content!");
return;
}


head = strsep(&head," ");

printf("2-->>head:%s\n