嘿!我試圖連接到我的本地主機和我在那裏的索引頁面。但每次我嘗試我的時間只是得到:使用winsock獲取本地主機的內容
Dados -> HTTP/1.1 400 Bad Request Date: Thu, 16 Apr 2009 15:25:41 GMT Server: Apache/2.2.10 (Win32) PHP/5.2.8 Content-Length: 226 Connection: close Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>400 Bad Request</title> </head><body> <h1>Bad Request</h1> <p>Your browser sent a request that this server could not understand.<br /> </p> </body></html>
☺
下面是我的代碼有:
#define WIN32_LEAN_AND_MEAN
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
int main()
{
WSADATA WsaDat;
if(WSAStartup(MAKEWORD(2,0),&WsaDat)!=0)
{
printf("Winsock error - Winsock initialization failed\r\n");
WSACleanup();
system("PAUSE");
return 0;
}
SOCKET Socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(Socket==INVALID_SOCKET)
{
printf("Winsock error - Socket creation Failed!\r\n");
WSACleanup();
system("PAUSE");
return 0;
}
struct hostent *host;
if((host=gethostbyname("localhost"))==NULL)
{
printf("Failed to resolve hostname.\r\n");
WSACleanup();
return 0;
}
printf("Resolveu o hostname\r\n");
SOCKADDR_IN SockAddr;
SockAddr.sin_port= htons(80);
SockAddr.sin_family= AF_INET;
SockAddr.sin_addr.s_addr= *((unsigned long*)host->h_addr);
if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr))!=0)
{
printf("Failed to establish connection with server\r\n");
WSACleanup();
system("PAUSE");
return 0;
}
char get[] = {
"GET/HTTP/1.1\n"
"From: [email protected]\n"
"User-Agent: HTTPTool/1.0\n"
"\n"
};
send(Socket,get, strlen(get),0);
printf("Ligou-se\r\n");
char buffer[1000];
int nDataLength = recv(Socket,buffer,1000,0);
printf("Dados -> %s",buffer);
shutdown(socket,SD_SEND);
closesocket(socket);
WSACleanup();
return 0;
}
有缺什麼?我正在學習一個教程,這基本上是他們在那裏的代碼。
由於
謝謝!它爲本地主機工作,但不適用於其他網站(比如本地主機)要嘗試閱讀更多關於http的內容。 – AntonioCS 2009-04-16 23:10:41