Reputation: 125
std::string HTTPrequest = "GET /index.html HTTP/1.1\r\nHost: www.yahoo.com\r\nConnection: close\r\n\r\n";
write(socket, HTTPrequest.c_str(), sizeof(HTTPrequest));
char pageReceived[4096];
int bytesReceived = read(socket, pageReceived, 4096);
I've got an HTTP client program that I run from my terminal. I've also got a webserver program. Using the webserver as a test, I can verify that the socket creation and attachment works correctly.
I create the request as shown above, then write to the socket. Using print statements, I can see that the code moves beyond the write call. However, it hangs on the read call.
I can't figure out what's going on - my formatting looks correct on the request.
Any ideas? Everything seems to work perfectly fine when I connect to my webserver, but both www.yahoo.com and www.google.com cause a hang. I'm on Linux.
Upvotes: 4
Views: 258
Reputation: 182885
In C and C++, sizeof
gives you the number of bytes required to hold a type, regardless of its contents. So you are not sending the full request, only sizeof(std::string)
bytes. You want HTTPRequest.size()
(which gives you the number of bytes the value stored in HTTPRequest
takes), not sizeof(HTTPrequest)
(which gives you the number of bytes a std::string
itself requires).
Upvotes: 3