Add reference first
# Include " Winsock2.h " // Header
# Pragma Comment (Lib, "ws2_32.lib ") // Lib
CalledCode:
Bool httpclient (STD :: String & Rest) // Receive character data returned with Parameters
{
STD :: String Errmsg; // Error message record
Wsadata;
Socket sock;
Sockaddr_in tcpaddr;
Hostent * Remotehost;
Char Host [] = { " 192.168.1.1 " }; // The host name is written directly.
Int RET, L;
Bool done;
Int Port = 80 ;
Int Chars = 0 ;
Char Buffer [ 1024 ];
If (Ret = Wsastartup (makeword ( 1 , 1 ), & Wsadata )) ! = 0 )
{
Errmsg + = " Wsastartup failed with error " + RET;
Return 1 ;
}
If (Remotehost = Gethostbyname (host )) = Null) // Obtain the address through the host name
{
Errmsg + = " Gethostbyname error! \ N " ;
Return 1 ;
}
Sock=Socket (af_inet, sock_stream,0);
Tcpaddr. sin_family = Af_inet;
Tcpaddr. sin_port = Htons (unsigned Short ) Port );
Tcpaddr. sin_addr.s_addr = * (Unsigned Long * ) * Remotehost -> H_addr_list ); // Conversion address
If (Connect (sock ,( Const Sockaddr * ) & Tcpaddr, Sizeof (Tcpaddr )))
{
Errmsg + = " Connect error! " ;
Return 1 ;
}
// Here is the HTTP header to be sent
Sendstring (sock, " GET/HTTP/1.1 \ r \ n " );
Sendstring (sock, " HOST: 192.168.1.1 \ r \ n " );
Sendstring (sock, " Accept: */* \ r \ n " );
Sendstring (sock, " User-Agent: Mozilla/4.0 " );
Sendstring (sock, " (Compatible; MSIE 7.00; Windows 98) \ r \ n " );
Sendstring (sock, " Connection: keep-alive \ r \ n " );
Sendstring (sock, " \ R \ n " );
Sendstring (sock, " \ R \ n " ); // Add blank lines at last
Done = False;
// File * FP;
// Fp = fopen ("1.txt"," W ");
// Print and save the HTTP Response Header
STD :: String STR;
While ( ! Done)
{
L = Recv (sock, buffer, 1 , 0 ); // One byte and one byte accept the HTTP Header
Str + = * Buffer;
If (L < 0 )
Done = True;
Switch ( * Buffer)
{
Case ' \ R ' :
Break ;
Case ' \ N ' : // Determine whether the HTTP header is accepted
If (Chars = 0 )
Done = True;
Chars = 0 ;
Break ;
Default :
Chars ++ ;
Break ;
}
Printf ( " % C " , STR );
// Fputc (buffer [0], FP );
}
// Receive body
Int Sum = 0 ;
Do
{
L = Recv (sock, buffer, 1024 , 0 );
If (L < 0 )
Break ;
Sum + = L;
Str. append (buffer, L );
// * (Buffer + l) = 0;
// Fputs (buffer, FP );
} While (L > 0 );
//The size of the output body is the same as the Content-Length in the response message header.
//In this way, you can check whether the acceptance is complete.
Printf ("Sum = % d \ n", Sum );
Closesocket (sock );
If(Wsacleanup ()=Socket_error)
{
Errmsg+ ="Wsacleanup failed with error"+Wsagetlasterror ();
}
Rest=STR;
Return 1;
}
VoidSendstring (socket sock, lpcstr Str)
{
Send (sock, STR, strlen (STR ),0);
}