-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpUnderstanding.cpp
More file actions
128 lines (99 loc) · 2.72 KB
/
Copy pathHttpUnderstanding.cpp
File metadata and controls
128 lines (99 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#include <string>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
void initWinsock(){
WSADATA wsa;
int result = WSAStartup(MAKEWORD(2,2),&wsa);
if(result!=0){
throw runtime_error("WSAStartup failed");
}
}
addrinfo* resolveHost(const string &host, int port){
addrinfo hints{};
hints.ai_family = AF_INET; //IPV4
hints.ai_socktype = SOCK_STREAM; // TCP
addrinfo* result = nullptr;
string portstr = to_string(port);
int res = getaddrinfo(host.c_str(),portstr.c_str(),&hints,&result);
if(res!=0){
throw std::runtime_error("DNS resolution failed");
}
return result;
}
SOCKET connectSocket(addrinfo* addr){
SOCKET sock = socket(
addr->ai_family,
addr->ai_socktype,
addr->ai_protocol
);
if(sock == INVALID_SOCKET){
throw runtime_error("Socket creation failed");
}
if(connect(sock,addr->ai_addr,(int)addr->ai_addrlen) == SOCKET_ERROR){
closesocket(sock);
throw runtime_error("Connection failed");
}
return sock;
}
string BuildHttpRequest(const string &host){
string req;
req += "GET /get HTTP/1.0\r\n";
req += "Host: " + host + "\r\n";
req += "Connection: close\r\n";
req += "\r\n";
return req;
}
void sendAll(SOCKET sock , const string &data){
int totalSent = 0;
int len = (int)data.size();
while(totalSent < len){
int sent = send(
sock,
data.c_str() + totalSent,
len - totalSent,
0
);
if(sent == SOCKET_ERROR){
throw runtime_error("Send failed");
}
totalSent += sent;
}
}
std::string receiveAll(SOCKET sock) {
std::string response;
char buffer[4096];
while (true) {
int received = recv(sock, buffer, sizeof(buffer), 0);
if (received == 0) {
break; // connection closed
}
if (received < 0) {
throw std::runtime_error("Receive failed");
}
response.append(buffer, received);
}
std::cout << "Response size: " << response.size() << "\n";
return response;
}
int main() {
try {
initWinsock();
std::string host = "httpbin.org";
int port = 80;
addrinfo* addr = resolveHost(host, port);
SOCKET sock = connectSocket(addr);
std::string request = BuildHttpRequest(host);
sendAll(sock, request);
std::string response = receiveAll(sock);
std::cout << response << "\n";
closesocket(sock);
freeaddrinfo(addr);
WSACleanup();
}
catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
}
}