#include #include #include #include #include #include #include #include using namespace std::literals; #include #include void die(const char *format, ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); exit(1); } void summarizeHttpResponse(const std::string &response) { auto eos = response.find("\r\n"); auto eoh = response.find("\r\n\r\n"); if (eos != std::string::npos && eoh != std::string::npos) { std::string status (response.data() , eos ); std::string headers (response.data() + eos + 2, eoh - eos - 2); std::string body (response.data() + eoh + 4, response.length() - eoh - 4); printf("%s\n", status.data()); if (std::smatch m; std::regex_search(headers, m, std::regex("(?:^|\n)(Location:.*)"))) printf("%s\n", m[1].str().data()); if (std::smatch m; std::regex_search(body, m, std::regex("\\s][^]*?"))) printf("\n%s\n", m[0].str().data()); } else printf("%s", response.data()); } int main(int argc, char **argv) { if (argc != 2) die("Usage: %s \n", argv[0]); addrinfo *res; if (int ec = getaddrinfo(argv[1], "http", 0, &res)) die("getaddrinfo failed: %s\n", gai_strerror(ec)); int sock = socket(res->ai_family, SOCK_STREAM, 0); if (connect(sock, res->ai_addr, res->ai_addrlen) != 0) die("connect failed: %s\n", strerror(errno)); freeaddrinfo(res); std::string httpRequest; httpRequest += "GET / HTTP/1.1\r\n"; httpRequest += "Host: "s + argv[1] + "\r\n"; httpRequest += "Connection: close\r\n"; httpRequest += "\r\n"; write(sock, httpRequest.data(), httpRequest.length()); std::string response; while (1) { char buf[2048]; int cnt = read(sock, buf, 2048); if (cnt <= 0) break; response += std::string_view(buf, cnt); } summarizeHttpResponse(response); shutdown(sock, SHUT_RDWR); close(sock); return 0; }