您好我在c中构建一个原始浏览器,这是一个非常简单的任务。我试图让我的客户端简单地从我请求的服务器读出响应消息。我试图从www.yahoo.com获得一个简单的回复。我已经尝试了许多不同的请求消息,这些消息都已成功发送。以下请求消息如下。
GET http://www.yahoo.com HTTP/1.1\r\n
Host: www.yahoo.com:80\r\n
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n
Accept-Language: en-us,en;q=0.5\r\n
Accept-Encoding: gzip, deflate\r\n
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n
Connection: keep-alive\r\n
和
GET http://www.yahoo.com HTTP/1.1
Host: www.yahoo.com:80
问题在于我没有从服务器中恢复()任何字节。但是,recv()不会导致错误为-1。相反,服务器并不想回应。以下是我的代码。
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#define MAXDATASIZE 500;
int main(int argc, char *argv[]){
struct addrinfo serverSide,*serverInfo;
int mySock, status;
char buf[501],ipstr[INET6_ADDRSTRLEN];
memset(&serverSide, 0, sizeof serverSide);
serverSide.ai_family = AF_UNSPEC;
serverSide.ai_socktype = SOCK_STREAM;
if(getaddrinfo("www.yahoo.com","80",&serverSide,&serverInfo)==0){
printf("get addr success\n");
}
mySock = socket(serverInfo->ai_family, serverInfo->ai_socktype, serverInfo->ai_protocol);
connect(mySock, serverInfo->ai_addr, serverInfo->ai_addrlen);
char msg[500] = "GET / HTTP/1.1\r\n";
strcat(msg," Host: www.yahoo.com:80\r\n");
printf("%s\n",msg);
if((status = send(mySock,msg,strlen(msg),0))== -1){
printf("request not sent %d\n",status);
perror("\n");
}else{
if((status = recv(mySock, buf, 500, 0))== -1){
printf("recieved byte error");
}else{
printf("%s\n Number of bytes recieved %d\n",buf,status);
}
}
close(mySock);
freeaddrinfo(serverInfo);
return 0;
}
任何帮助都会很棒。谢谢!
答案 0 :(得分:6)
HTTP协议要求发送2个回车符/换行符以结束HTTP请求
我在你的问题中没有看到它们
答案 1 :(得分:2)
标题后必须有两个换行符:strcat(msg,"Host: www.yahoo.com:80\r\n\r\n");
recv()
返回0。AF_INET
代替AF_UNSPEC
。同时检查socket()
和connect()
返回值,例如(包括errno.h,stdlib.h):
if (mySocket == -1) {
perror("Creating socket failed");
exit(EXIT_FAILURE);
}