c语言利用socket实现http请求

最近由于项目原因,需要自己在c代码里面实现http请求并对返回数据进行解析。

现将相关代码记录如下

主要代码:

#include 
#include 
#include 
#include  
#include 
#include 
#include 
#include 
int main(int argc, char *argv[]){ 
    if(argc!=2){
      printf("请输入正确ip\n"); 
      return 1;
    } 
    int sockfd;
    int len; 
    struct sockaddr_in address; 
    int result; 
    char httpstring[100]; 
    sprintf(httpstring,"GET / HTTP/1.1\r\n"
          "Host: %s\r\n"
          "Connection: Close\r\n\r\n",argv[1]); 
    char ch; 
    sockfd = socket(AF_INET, SOCK_STREAM, 0); 
    address.sin_family = AF_INET; 
    address.sin_addr.s_addr = inet_addr(argv[1]); 
    address.sin_port = htons(80); 
    len = sizeof(address);
    result = connect(sockfd,(struct sockaddr *)&address,len); 
    if(result == -1){ 
       perror("connect error"); 
       return 1; 
    }
    write(sockfd,httpstring,strlen(httpstring)); 
    while(read(sockfd,&ch,1)){ 
      printf("%c", ch); 
    } 
    close(sockfd); 
    printf("\n"); 
    return 0; 
 }

连接csdn官网示例:

c语言利用socket实现http请求_第1张图片

c语言利用socket实现http请求_第2张图片

另附返回数据解析代码:

char sourceData[1024*1024];//原始数据
char lengthTemp[1024*1024];
char desData[1024*1024];//目的数据
char *strTemp;
int iDataLen;
strTemp = strstr(sourceData, "ConTent-Length:");
for(iPos=0;iPos < getLength(strTemp);iPos++)//getLength为自定义函数
{
    if(strTemp[iPos] == '\n' || strTemp[iPos] == '\r')
    memcpy(lengthTemp, strTemp+strlen("Content-Length:"), iPos - strlen("Content-Length:"));
    printf("长度串:%s\n",lengthTemp);
    iDataLen = atoi(lengthTemp);
    break;
}

//获取目的数据
strncpy(desData, sourceData + strlen(sourceData) - iDataLen, sizeof(desData));

你可能感兴趣的:(Sundries,c,http,socket,http请求,linux)