winsock请求http
2021-05-07 21:27
标签:ada har ast scan readline i++ null argv inet_addr winsock请求http 标签:ada har ast scan readline i++ null argv inet_addr 原文地址:http://www.cnblogs.com/hatsusakana/p/7639595.htmlint 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;
}
上一篇:C#文件上传