我正在学习在OS X机器上的C和C ++中使用本机套接字。在上一个项目中,我在http://castifyreceiver.com/index.html上建立了一个非常简单的网页。该网页几乎不再执行任何操作,因此我不介意共享真实的URL。
基本上我的问题是我所有的HTTP请求都返回400 Bad Request。我知道用于此练习的网页已启动并正在运行,并且可以通过浏览器访问该网页。这使我相信我在错误地实现了HTTP协议,但是我不知道哪里出了问题。
以下是我用于通过套接字请求此页面的所有代码。
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
int main(int argc, const char * argv[]) {
// create the request
const char * request = "GET /index.html HTTP/1.1\nAccept: */*\n\n";
size_t length = strlen(request);
printf("request:\n\n%s", request);
// get the destination address
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
struct addrinfo * address;
getaddrinfo("castifyreceiver.com", "http", &hints, &address);
// create a socket
int sfd = socket(address->ai_family, address->ai_socktype, address->ai_protocol);
int result = connect(sfd, address->ai_addr, address->ai_addrlen);
if (result != 0) {
printf("connection failed: %i\n", result);
freeaddrinfo(address);
close(sfd);
return 0;
} else {
printf("connected\n");
}
// write to socket
ssize_t written = write(sfd, request, length);
printf("wrote %lu of %lu expected\n", written, length);
// read from socket and cleanup
char response[4096];
ssize_t readed = read(sfd, response, 4096);
printf("read %lu of 4096 possible\n", readed);
close(sfd);
freeaddrinfo(address);
// display response message
response[readed] = '\0';
printf("response:\n\n%s\n", response);
return 0;
}
该程序始终输出类似于以下内容的内容:
request:
GET /index.html HTTP/1.1
Accept: */*
connected
wrote 38 of 38 expected
read 590 of 4096 possible
response:
HTTP/1.1 400 Bad Request
Date: Thu, 05 Nov 2015 18:24:08 GMT
Server: Apache/2.2.31 (Unix) mod_ssl/2.2.31 OpenSSL/1.0.1e-fips mod_bwlimited/1.4
Content-Length: 357
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>
<hr>
<address>Apache/2.2.31 (Unix) mod_ssl/2.2.31 OpenSSL/1.0.1e-fips mod_bwlimited/1.4 Server at 108.167.131.50 Port 80</address>
</body></html>
我花了很多时间查看RFC 2616,但仍然找不到我做错的事情。任何帮助表示赞赏。
两件事情:
您必须发送Host
标头,参见。RFC 2616第 129:
客户端必须在所有HTTP / 1.1请求消息中包括主机标头字段。如果所请求的URI不包括所请求服务的Internet主机名,则必须为Host头字段提供一个空值。
使用\r\n
终止您行HTTP,而不是仅仅的\n
,比照。RFC 2616第 16:
HTTP / 1.1将序列CR LF定义为除实体主体之外的所有协议元素的行尾标记(有关允许的应用程序,请参见附录19.3)。实体中的行尾标记由其关联的媒体类型定义,如3.7节所述。
如果您更改它,它应该可以工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句