Question: Write a Windows Socket program that is capable of requesting and receiving the default HTML page from a web server. The program should prompt the
Write a Windows Socket program that is capable of requesting and receiving the default HTML page from a web server. The program should prompt the user to input the web server hostname (for example www.facebookcom) from the keyboard and print the web server IP address as well as the total number of bytes received. The program may NOT print the HTML page.
Here is what I have so far. Please format as in the picture.
#include
#include
#include
#include
using namespace std;
#pragma comment(lib, "Ws2_32.lib") // link project
#define BUFFERSIZE 513
int main()
{
// initialize
int iResult;
WSADATA wsaData;
struct addrinfo hints, *result;
SOCKET sock; //socket handle
char sendBuffer[BUFFERSIZE];
char recvBuffer[BUFFERSIZE];
char hostname[NI_MAXHOST] = "www.facebook.com";
//initialize the winsock library
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d ", iResult);
return 1;
}
memset(&hints, 0, sizeof(hints)); //in bytes, create memory space
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
iResult = getaddrinfo(hostname, 80, &hints, &result);
if (iResult != 0){
printf("getaddrinfo faild! with an error", iResult);
WSACleanup();
return 1;
}
sock = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (sock == INVALID_SOCKET){
printf("socket failed with an error: %d ", WSAGetLastError());
WSACleanup();
return -1;
}
iResult = connect(sock, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(sock);
WSACleanup();
return 1;
}
// prepare an http request
strcpy_s(sendBuffer, "GET/HTTP/1.1 ");
strcat_s(sendBuffer, "Host: ");
strcat_s(sendBuffer, hostname);
strcat_s(sendBuffer, " ");
strcat_s(sendBuffer, " ");
//sending the request
iResult = send(sock, sendBuffer, strlen(sendBuffer), 0);
if (iResult == SOCKET_ERROR) {
closesocket(sock);
WSACleanup();
return 1;
}
printf("total byte sent: %d ", iResult);
int recvlen = BUFFERSIZE;
//receiving data from the
do{
iResult = recv(sock, recvBuffer, (int)strlen(recvBuffer) - 1, 0);
if (iResult > 0){
recvBuffer[iResult] = '\0';
printf("%s", recvBuffer);
}
} while (iResult > 0);
printf("%n");
closesocket(sock);
WSACleanup();
system ("PAUSE");
return 0;
}

The request should be formatted as followed: "GET /HTTP/1.11rIn" HOS server hosinrm rin ln" rin
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
