#include <iostream>
#include <string>
#include <stdexcept>
#include <cstring>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
/*
Creates a TCP connection to the given host and port.
Returns a connected socket file descriptor.
This uses POSIX sockets:
- getaddrinfo: resolve hostname
- socket: create TCP socket
- connect: establish connection
*/
int connectToHost(const std::string& host, const std::string& port) {
addrinfo hints{};
hints.ai_family = AF_UNSPEC; // Allow IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP
addrinfo* result;
if (getaddrinfo(host.c_str(), port.c_str(), &hints, &result) != 0) {
throw std::runtime_error("Failed to resolve host");
}
int sockfd = -1;
for (addrinfo* rp = result; rp != nullptr; rp = rp->ai_next) {
sockfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sockfd == -1) continue;
if (connect(sockfd, rp->ai_addr, rp->ai_addrlen) == 0) {
break; // success
}
close(sockfd);
sockfd = -1;
}
freeaddrinfo(result);
if (sockfd == -1) {
throw std::runtime_error("Failed to connect to host");
}
return sockfd;
}
// Removes chunked transfer encoding from an HTTP body.
// Input example:
// "1c\r\nhttps://tinyurl.com/27aunsef\r\n0\r\n"
// Output:
// "https://tinyurl.com/27aunsef"
std::string decodeChunked(const std::string& body) {
std::string result;
std::size_t pos = 0;
while (pos < body.size()) {
// Find the chunk size (hex)
std::size_t lineEnd = body.find("\r\n", pos);
if (lineEnd == std::string::npos) break;
// Extract hex number
std::string hexSize = body.substr(pos, lineEnd - pos);
int chunkSize = std::stoi(hexSize, nullptr, 16);
// Zero-size chunk means end
if (chunkSize == 0) break;
// Move to chunk data
pos = lineEnd + 2;
// Append chunk data
if (pos + chunkSize <= body.size()) {
result.append(body, pos, chunkSize);
}
// Move past chunk data + CRLF
pos += chunkSize + 2;
}
return result;
}
/*
Sends an HTTP GET request to TinyURL's API using raw sockets.
Reads the response and extracts the body (the shortened URL).
This approach:
- Builds a valid HTTP/1.1 request
- Reads until the server closes the connection
- Splits headers from body
*/
std::string shortenURL(const std::string& longURL) {
const std::string host = "tinyurl.com";
const std::string port = "80";
const std::string target = "/api-create.php?url=" + longURL;
int sockfd = connectToHost(host, port);
// Build HTTP request
std::string request =
"GET " + target + " HTTP/1.1\r\n"
"Host: " + host + "\r\n"
"User-Agent: RawSocketClient\r\n"
"Connection: close\r\n"
"\r\n";
// Send request
if (send(sockfd, request.c_str(), request.size(), 0) == -1) {
close(sockfd);
throw std::runtime_error("Failed to send request");
}
// Read response
std::string response;
char buffer[4096];
while (true) {
ssize_t bytes = recv(sockfd, buffer, sizeof(buffer), 0);
if (bytes <= 0) break;
response.append(buffer, bytes);
}
close(sockfd);
// Find the body (after "\r\n\r\n")
std::size_t pos = response.find("\r\n\r\n");
if (pos == std::string::npos) {
throw std::runtime_error("Invalid HTTP response");
}
std::string rawBody = response.substr(pos + 4);
std::string shortURL = decodeChunked(rawBody);
return shortURL;
}
int main() {
try {
std::string longURL =
"https://www.example.com/some/very/long/path?with=query¶meters=true";
std::string shortURL = shortenURL(longURL);
std::cout << "Original URL:\n" << longURL << "\n\n";
std::cout << "Shortened URL:\n" << shortURL << "\n";
}
catch (const std::exception& ex) {
std::cerr << "Error: " << ex.what() << "\n";
return 1;
}
}
/*
run:
Original URL:
https://www.example.com/some/very/long/path?with=query¶meters=true
Shortened URL:
https://tinyurl.com/27aunsef
*/