Here is how we can build a basic HTTP proxy in C++ in 30 lines of code:
First include the required headers:
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string>
Next, create a listening socket:
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8080);
bind(server_fd, (struct sockaddr *)&address, sizeof(address));
listen(server_fd, 3);
In a loop, accept a connection:
int client_fd = accept(server_fd, (struct sockaddr *)&address, sizeof(address));
Receive the HTTP request:
char buffer[4096];
recv(client_fd, buffer, 4096, 0);
Extract the URL to proxy:
std::string url = std::string(strtok(buffer, " "));
Make the proxied request:
std::string response = makeRequest(url);
Send back the response:
send(client_fd, response.c_str(), response.size(), 0 );
This implements a basic HTTP proxy in C++ in under 30 lines.
Here is the full code
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string>
int main() {
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8080);
bind(server_fd, (struct sockaddr *)&address, sizeof(address));
listen(server_fd, 3);
while(true) {
int client_fd = accept(server_fd, (struct sockaddr *)&address, sizeof(address));
char buffer[4096];
recv(client_fd, buffer, 4096, 0);
std::string url = std::string(strtok(buffer, " "));
std::string response = makeRequest(url);
send(client_fd, response.c_str(), response.size(), 0 );
}
}
This is great as a learning exercise but it is easy to see that even the proxy server itself is prone to get blocked as it uses a single IP. In this scenario where you may want a proxy that handles thousands of fetches every day using a professional rotating proxy service to rotate IPs is almost a must.
Otherwise, you tend to get IP blocked a lot by automatic location, usage, and bot detection algorithms.
Our rotating proxy server Proxies API provides a simple API that can solve all IP Blocking problems instantly.
Hundreds of our customers have successfully solved the headache of IP blocks with a simple API.
The whole thing can be accessed by a simple API like below in any programming language.
In fact, you don't even have to take the pain of loading Puppeteer as we render Javascript behind the scenes and you can just get the data and parse it any language like Node, Puppeteer or PHP or using any framework like Scrapy or Nutch. In all these cases you can just call the URL with render support like so:
curl "<http://api.proxiesapi.com/?key=API_KEY&render=true&url=https://example.com>"
We have a running offer of 1000 API calls completely free. Register and get your free API Key.