Last active
August 20, 2021 15:09
-
-
Save Ben-0-mad/5abd651dbf8ef2e9f32b254463156bf2 to your computer and use it in GitHub Desktop.
Example of HTTP GET request using winsock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <WS2tcpip.h> | |
#pragma comment (lib, "ws2_32.lib") | |
// Example of HTTP GET request using windows sockets | |
// Author: Maniclout | |
void getrequest() { | |
std::string ipAddress = "www.example.com"; | |
int port = 80; | |
// initialise winsock | |
WSADATA data; | |
WORD ver = MAKEWORD(2, 2); | |
int wsResult = WSAStartup(ver, &data); | |
if (wsResult != 0) { | |
std::cerr << "Can't start winsock, Err #" << wsResult << std::endl; | |
return; | |
} | |
// create socket | |
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, 0); | |
if (clientSocket == INVALID_SOCKET) { | |
std::cerr << "Can't create socket, Err #" << WSAGetLastError() << std::endl; | |
WSACleanup(); | |
return; | |
} | |
// hint structure | |
sockaddr_in hint; | |
hint.sin_family = AF_INET; | |
hint.sin_port = htons(port); | |
inet_pton(AF_INET, ipAddress.c_str(), &hint.sin_addr); | |
// connect | |
int connResult = connect(clientSocket, (sockaddr*)&hint, sizeof(hint)); | |
if (connResult == SOCKET_ERROR) { | |
std::cerr << "Can't connect to server, Err #" << WSAGetLastError << std::endl; | |
closesocket(clientSocket); | |
WSACleanup(); | |
return; | |
} | |
// do while loop to send and receive data | |
char buff[4096]; | |
char cmd[] = "GET /index.html HTTP/1.0\r\nHost: example.com\r\n\r\n"; | |
int sendResult = send(clientSocket, cmd, sizeof(cmd), 0); | |
if (sendResult != SOCKET_ERROR) { | |
// wait for response | |
ZeroMemory(buff, 4096); | |
int bytesReceived = recv(clientSocket, buff, 4096, 0); | |
// echo response to console | |
if (bytesReceived > 0) { | |
std::cout << std::string(buff, 0, bytesReceived) << std::endl; | |
} | |
} | |
closesocket(clientSocket); | |
WSACleanup(); | |
return; | |
} | |
int main(){ | |
getrequest(); | |
std::cin.get(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment