码迷,mamicode.com
首页 > Windows程序 > 详细

winsock请求http

时间:2017-10-09 10:01:56      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:ada   har   ast   scan   readline   i++   null   argv   inet_addr   

int socket_readline(SOCKET socket,char *head)  
{  
    char c = ‘\0‘;  
    int r = 0,i = 0;  
    while(recv(socket,&c,1,0)>0)  
    {  
        if(r == 1)  
        {  
            if(c == ‘\n‘)  
            {  
                break;  
            }  
            else  
            {  
                r = 0;  
            }  
        }  
        else if(c == ‘\r‘)  
        {  
            r = 1;  
        }  
        else head[i++] = c;  
    }  
    head[i] = ‘\0‘;  
    if(strcmp(head,"\r\n") == 0) return -1;  
    else return i;  
}  

int main(int argc, char* argv[])
{
	WSADATA wsaData;
	WORD sockVersion = MAKEWORD(2,0);
	WSAStartup(sockVersion,&wsaData);
	SOCKET s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(s==INVALID_SOCKET)
	{
		return -1;
	}
	sockaddr_in servAddr;
	servAddr.sin_family=AF_INET;
	servAddr.sin_port=htons(80);   
	servAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
	if(connect(s,(sockaddr*)&servAddr,sizeof(servAddr))==-1)
	{
		return -1;
	}

	char *httpHead = 
		"GET / HTTP/1.1\r\n"
		"Host: 127.0.0.1\r\n"  
        "Connection: Keep-Alive\r\n"  
		"\r\n";
	send(s,httpHead,strlen(httpHead),0);

	char *http_head_recv = new char[3000];  
    int Content_Length = 0;  
    for(int flag=1;flag>0;)  
    {  
        memset(http_head_recv,0,3000);  
        flag = socket_readline(s,http_head_recv);  
        if(strstr(http_head_recv,"Content-Length:") != NULL){  
            sscanf(http_head_recv,"Content-Length: %d",&Content_Length);  
        }  
        printf("%s\n",http_head_recv);  
    }  
    free(http_head_recv);

	if(Content_Length>0)
	{
		char *msg = new char[Content_Length+1];
		memset(msg,0,Content_Length+1);
		recv(s,msg,Content_Length,0);
		msg[Content_Length] = ‘\0‘;
		printf("%s\n",msg);
		free(msg);
	}

	closesocket(s);
	WSACleanup();
	return 0;
}

  

winsock请求http

标签:ada   har   ast   scan   readline   i++   null   argv   inet_addr   

原文地址:http://www.cnblogs.com/hatsusakana/p/7639595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!