Why does this socket function only read the first 1440 chars of the stream. Why not the whole stream ? I checked it with gdm and valgrind and everything seems correct...
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
int main(void)
{
// set family and socket type
struct addrinfo hints, *result;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
// resolve hostname to IP address: specify host and port number (in char not int)
if(getaddrinfo("www.unix.com", "80", &hints, &result) != 0)
{
freeaddrinfo(result);
puts("Could not resolve hostname.");
exit(1);
}
// create socket and free addrinfo memory
int newsocket = socket(result->ai_family, result->ai_socktype, 0);
if(newsocket == -1)
{
puts("Could not create socket.");
freeaddrinfo(result); // free addrinfo memory
close(newsocket);
exit(1);
}
// set socket timeouts
struct timeval timeout;
memset(&timeout, 0, sizeof(timeout)); // zero timeout struct before use
timeout.tv_sec = 5;
timeout.tv_usec = 0;
setsockopt(newsocket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); // send timeout
setsockopt(newsocket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); // receive timeout
// connect to website
if(connect(newsocket, result->ai_addr, result->ai_addrlen) == -1)
{
puts("Could not connect.");
freeaddrinfo(result); // free addrinfo memory
close(newsocket);
exit(1);
}
// send headers to connection
char headers[256] = "GET /index HTTP/1.1\r\nHost: www.unix.com\r\nUser-Agent: Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0)\r\nReferer: \r\nConnection: Close\r\n\r\n";
if( (send(newsocket, headers, strlen(headers), 0)) == -1 )
{
puts("Could not send data.");
freeaddrinfo(result); // free addrinfo memory
close(newsocket);
exit(1);
}
// receive webpage from connection
char response[51201] = "";
ssize_t length = recv(newsocket, response, 51200, 0);
response[strlen(response)] = '\0'; // terminate the string
if(length == -1)
{
puts("Could not receive data.");
freeaddrinfo(result); // free addrinfo memory
close(newsocket);
exit(1);
}
// free addrinfo memory
freeaddrinfo(result);
// close socket
close(newsocket);
printf("%s\n%i\n", response, length);
return 0;
}