Advertisement
AntonioVillanueva

Funcion socket c++

Apr 8th, 2024
643
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. std::string sendNoCurl(const std::string& host, int port, const std::string& path,bool debug=false) {
  2.             int sock = socket(AF_INET, SOCK_STREAM, 0);
  3.             if (sock == -1) {
  4.                 std::cerr << "Error: Failed to create socket" << std::endl;
  5.                 return "";
  6.             }
  7.  
  8.             struct sockaddr_in server;
  9.             server.sin_family = AF_INET;
  10.             server.sin_port = htons(port);
  11.             if (inet_pton(AF_INET, host.c_str(), &server.sin_addr) <= 0) {
  12.                 std::cerr << "Error: Invalid address" << std::endl;
  13.                 close(sock);
  14.                 return "";
  15.             }
  16.  
  17.             if (connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0) {
  18.                 std::cerr << "Error: Connection failed" << std::endl;
  19.                 close(sock);
  20.                 return "";
  21.             }
  22.  
  23.             std::string request = "get " + path + " http/1.0\r\n";
  24.             //std::string request = "GET " + path + " HTTP/1.1\r\n";
  25.             request += "Host: " + host + "\r\n";
  26.             request += "Connection: close\r\n\r\n";
  27.  
  28.             cout <<"DEBUG NO CURL :"<<request<<endl;
  29.             if (send(sock, request.c_str(), request.length(), 0) != request.length()) {
  30.                 std::cerr << "Error: Failed to send request" << std::endl;
  31.                 close(sock);
  32.                 return "";
  33.             }
  34.  
  35.             std::string response;
  36.             char buffer[4096];
  37.             int bytes_received;
  38.             while ((bytes_received = recv(sock, buffer, sizeof(buffer), 0)) > 0) {
  39.                 response.append(buffer, bytes_received);
  40.             }
  41.  
  42.             close(sock);
  43.  
  44.             return response;
  45.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement