我试图通过套接字编程和C ++脚本访问Wikipedia页面。我能够访问服务器,但收到404错误通知我请求的URL不存在。只需在浏览器中输入相同的URL即可。
这是网址:http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
这是C ++脚本:
#include <iostream>
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
using namespace std;
int main()
{
int s, error;
char length[10];
length[0]=0;
struct sockaddr_in addr;
if((s = socket(AF_INET,SOCK_STREAM,0))<0)
{
cout<<"Error 01: creating socket failed!\n";
close(s);
return 1;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
inet_aton("204.27.61.92",&addr.sin_addr);
error = connect(s,(sockaddr*)&addr,sizeof(addr));
if(error!=0)
{
cout<<"Error 02: conecting to server failed!\n";
close(s);
return 1;
}
char msg[]="GET /wiki/Hypertext_Transfer_Protocol HTTP/1.1\nHOST: en.wikipedia.org\n\n"
int leng = send(s, msg, sizeof(msg), 0);
if(leng == -1)
cout<<"There is a problem!"<<endl;
send(s,msg,sizeof(msg),0);
char answ[1024];
ssize_t len;
while((len = recv(s, answ, 1024, 0)) > 0)
{
cout.write(answ, len);
}
cout << endl;
if(len < 0)
{
cout<<"Error!"<<endl;
}
close(s);
return 0;
}
该脚本整体运行良好。交换行
char msg[]="GET /wiki/Hypertext_Transfer_Protocol HTTP/1.1\nHOST: en.wikipedia.org\n\n";
与
char msg[] = "GET /beej/inet_ntoaman.html http/1.1\nHOST: retran.com\n\n";
无错误地检索请求的网站。我在这里错过了什么?为什么该脚本不适用于维基百科?
由于
答案 0 :(得分:1)
通过尝试实现HTTP 1.0,可以使事情变得更容易。