elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Arreglado, de nuevo, el registro del warzone (wargame) de EHN


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  Mi clase HTTP + winsock peticion HTTP ejemplo
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Mi clase HTTP + winsock peticion HTTP ejemplo  (Leído 3,041 veces)
patilanz


Desconectado Desconectado

Mensajes: 481

555-555-0199@example.com


Ver Perfil WWW
Mi clase HTTP + winsock peticion HTTP ejemplo
« en: 26 Diciembre 2014, 18:08 pm »

Hola acabo de hacer una clase para organizar mas o menos el header de una peticion HTTP. Como esto:

Citar
HTTP/1.1 200 OK\r\n
Date: Mon, 23 May 2005 22:38:34 GMT\r\n
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)\r\n
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT\r\n
ETag: "3f80f-1b6-3e1cb03b"\r\n
Content-Type: text/html; charset=UTF-8\r\n
Content-Length: 131\r\n
Connection: close\r\n
\r\n

HTTP_class.hpp
Código
  1. #ifndef HTTP_CLASS_HPP
  2. #define HTTP_CLASS_HPP
  3.  
  4. #include <string>
  5. #include <ctime>
  6. #include <vector>
  7.  
  8. using namespace std;
  9.  
  10.  
  11. //CLASS STATE
  12. #define SETUP_OK 1
  13. #define SETUP_NEED 2
  14. #define INVALID_HEADER 3
  15.  
  16.  
  17. //HTTP CODES
  18.  
  19. //Informational
  20. #define H_Continue 100
  21. #define H_Switching_Protocols 101
  22. #define H_Processing 102
  23.  
  24. //Success
  25. #define H_OK 200
  26. #define H_Created 201
  27. #define H_Accepted 202
  28. #define H_Non_Authoritative_Information 203
  29. #define H_No_Content 204
  30. #define H_Reset_Content 205
  31. #define H_Partial_Content 206
  32. #define H_Multi_Status 207
  33. #define H_Already_Reported 208
  34. #define H_IM_Used 226
  35.  
  36. //Redirection
  37. #define H_Multiple_Choices 300
  38. #define H_Moved_Permanently 301
  39. #define H_Found 302
  40. #define H_See_Other 303
  41. #define H_Not_Modified 304
  42. #define H_Use_Proxy 305
  43. #define H_Switch_Proxy 306
  44. #define H_Temporary_Redirect 307
  45. #define H_Permanent_Redirect 308
  46.  
  47. //Client Error
  48. #define H_Bad_Request 400
  49. #define H_Unauthorized 401
  50. #define H_Payment_Required 402
  51. #define H_Forbidden 403
  52. #define H_Not_Found 404
  53. #define H_Method_Not_Allowed 405
  54. #define H_Not_Acceptable 406
  55. #define H_Proxy_Authentication_Required 407
  56. #define H_Request_Timeout 408
  57. #define H_Conflict 409
  58. #define H_Gone 410
  59. #define H_Length_Required 411
  60. #define H_Precondition_Failed 412
  61. #define H_Request_Entity_Too_Large 413
  62. #define H_Request_URI_Too_Long 414
  63. #define H_Unsupported_Media_Type 415
  64. #define H_Requested_Range_Not_Satisfiable 416
  65. #define H_Expectation_Failed 417
  66. #define H_Im_a_teapot 418
  67. #define H_Authentication_Timeout 419
  68. #define H_Method_Failure 420
  69. #define Enhance_Your_Calm 420
  70. #define H_UnprocessableEntity 422
  71. #define H_Locked 423
  72. #define H_Failed_Dependency 424
  73. #define H_Upgrade_Required 426
  74. #define H_Precondition_Required 428
  75. #define H_Too_Many_Requests 429
  76. #define H_Request_Header_Fields_Too_Large 431
  77. #define H_Login_Timeout 440
  78. #define H_No_Response 444
  79. #define H_Retry_With 449
  80. #define H_Blocked_by_Windows_Parental_Controls 450
  81. #define H_Unavailable_For_Legal_Reasons 451
  82. #define H_Redirect 494
  83. #define H_Request_Header_Too_Large 495
  84. #define H_Cert_Error 496
  85. #define H_No_Cert 497
  86. #define H_HTTP_to_HTTPS 498
  87. #define H_Token_expired_invalid 499
  88. #define H_Client_Closed_Request 499
  89. #define H_Token_required 499
  90.  
  91.  
  92.  
  93. //class ContentType{
  94. //public:
  95. // string type;
  96. // string charset;
  97. //};
  98.  
  99.  
  100. class HTTP{
  101. public:
  102. HTTP();
  103. HTTP(string header);
  104. bool setup(string header);
  105. int Code();//HTTP status
  106. const int State();//class status
  107. tm Date();
  108. string Server();
  109. tm Last_Modified();
  110. string ETag();
  111. string Content_Type();
  112. int Content_Lenght();
  113. string Connection();
  114.  
  115. string Other(string name);
  116. vector<string> Other(int i);
  117.  
  118. //helpful functions
  119. double HTTPVersion();
  120. int Size();//Size of fields
  121.  
  122.  
  123. private:
  124. int state;//Already setup?
  125.  
  126. int code;
  127. tm date;
  128. string server;
  129. tm last_modified;
  130. string etag;
  131. string content_type;
  132. int content_length;
  133. string header;
  134. string connection;
  135.  
  136. vector < vector<string> > all; //all fields
  137.  
  138. //helpful data
  139. double version;
  140.  
  141. //Config functions
  142. tm getDate(string date);
  143. void defaultConfig();
  144. };
  145.  
  146.  
  147. vector<string> split(string full, string part); //helpful function
  148.  
  149.  
  150. #endif

HTTP_class.cpp
Código
  1. #include "http_class.hpp"
  2. #include <regex>
  3.  
  4. HTTP::HTTP(){
  5. defaultConfig();
  6. }
  7.  
  8. HTTP::HTTP(string header){
  9. defaultConfig();
  10. setup(header);
  11. }
  12.  
  13.  
  14. string HTTP::Other(string name){
  15. for (int i = 0; i < all.size(); i++){
  16. if (all[i][0] == name){
  17. return all[i][1];
  18. }
  19. }
  20. return "";
  21. }
  22. vector<string> HTTP::Other(int i){
  23. if (i < all.size())
  24. return all[i];
  25. else
  26. return vector<string>();
  27. }
  28.  
  29.  
  30. bool HTTP::setup(string header){
  31. vector<string> parts = split(header, "\r\n");
  32.  
  33. //all setup
  34. for (int i = 1; i < parts.size(); i++){
  35. all.push_back(split(parts[i],": " ));
  36. }
  37. all.pop_back();          // remove last 2 \r\n of the end of http protocol
  38. all.pop_back();          //
  39. //end
  40. if (all.size() < 1){ //Nothing founded
  41. state = INVALID_HEADER;
  42. return false;
  43. }
  44.  
  45. //http setup
  46. string v = parts[0].substr(5, 3);
  47. version = atof(v.c_str());
  48. code = atoi(parts[0].substr(8, 4).c_str());
  49. //end
  50. date = getDate(Other("Date"));
  51. server = Other("Server");
  52. last_modified = getDate(Other("Last-Modified"));
  53. etag = Other("ETag");
  54. content_type = Other("Content-Type");//Mejores en 2.0
  55. content_length = atoi(Other("Content-Length").c_str());
  56. connection = Other("Connection");
  57. state = SETUP_OK;
  58. return true;
  59. }
  60.  
  61.  
  62. int HTTP::Code(){
  63. return code;
  64. }
  65.  
  66. const int HTTP::State(){
  67. return state;
  68. }
  69.  
  70. tm HTTP::Date(){
  71. //Example of check
  72. if (date.tm_year != 0 && state == SETUP_OK){ // if == 0 no date in header
  73. return date;
  74. }
  75. }
  76. string HTTP::Server(){
  77. return server;
  78. }
  79. tm HTTP::Last_Modified(){
  80. return last_modified;
  81. }
  82. string HTTP::ETag(){
  83. return etag;
  84. }
  85. string HTTP::Content_Type(){
  86. return content_type;
  87. }
  88. int HTTP::Content_Lenght(){
  89. return content_length;
  90. }
  91. string HTTP::Connection(){
  92. return connection;
  93. }
  94.  
  95.  
  96. //Helpful functions
  97. double HTTP::HTTPVersion(){
  98. return version;
  99. }
  100. int HTTP::Size(){
  101. return all.size();
  102. }
  103.  
  104.  
  105.  
  106. tm HTTP::getDate(string _date){ //Get date in tm format for example in Date or Last-Modified
  107. tm date = tm();
  108. if (_date.size() > 0){
  109. const static string months[] = {
  110. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  111. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  112. };
  113. smatch match;
  114. if (_date.find("GMT") != -1){ // New format
  115. if (regex_search(_date, match, regex("^\\w{3,9},\\s(\\d{2})[\\s\\-](\\w{3})[\\s\\-](\\d{2,4})\\s(\\d{2}):(\\d{2}):(\\d{2}) GMT$"))){
  116. date.tm_mday = atoi(match[1].str().c_str());
  117. int month;
  118. for (int i = 0; i < sizeof(months); i++){
  119. if (months[i] == match[2].str()){
  120. month = i;
  121. break;
  122. }
  123. }
  124. date.tm_mon = month;
  125. int year = atoi(match[3].str().c_str());
  126. if (year > 1900)
  127. year -= 1900;
  128. date.tm_year = year;
  129. date.tm_hour = atoi(match[4].str().c_str());
  130. date.tm_min = atoi(match[5].str().c_str());
  131. date.tm_sec = atoi(match[6].str().c_str());
  132. }
  133. }
  134. else{ //Old ANSI format
  135. if (regex_search(_date, match, regex("^\\w{3} (\\w{3})  (\\d{1,2}) (\\d{2}):(\\d{2}):(\\d{2}) (\\d{4})$"))){
  136. int month;
  137. for (int i = 0; i < sizeof(months); i++){
  138. if (months[i] == match[1].str()){
  139. month = i;
  140. break;
  141. }
  142. }
  143. date.tm_mday = atoi(match[2].str().c_str());
  144. date.tm_hour = atoi(match[3].str().c_str());
  145. date.tm_min = atoi(match[4].str().c_str());
  146. date.tm_sec = atoi(match[5].str().c_str());
  147. date.tm_year = atoi(match[6].str().c_str());
  148. }
  149. }
  150. }
  151. return date;
  152. }
  153.  
  154.  
  155. void HTTP::defaultConfig(){ //Set some values help to don't check state in every function
  156. state = SETUP_NEED;
  157. code = 0;
  158. version = 0;
  159. content_length = 0;
  160.  
  161. }
  162.  
  163.  
  164.  
  165. //split string in vector
  166.  
  167. vector<string> split(string full, string part){
  168. vector<string> parts;
  169. int last = 0;
  170. int p;
  171. while ((p = full.find(part, last)) != -1){
  172. parts.push_back(full.substr(last, p - last));
  173. last = p + part.size();
  174. }
  175. parts.push_back(full.substr(last, full.size()));
  176. return parts;
  177. }

Ejemplo conexión http con win sockets
Código
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <WinSock2.h>
  5. #include "http_class.hpp"
  6.  
  7. #pragma comment(lib,"ws2_32.lib")
  8.  
  9. using namespace std;
  10.  
  11. #define SIZE 1024
  12.  
  13. int main(){
  14. WSADATA wsadata;
  15. WSAStartup(MAKEWORD(2, 2), &wsadata);
  16. char buffer[SIZE];
  17.  
  18.  
  19.  
  20. vector<vector<string>>links = { //Random urls
  21. { "foro.elhacker.net", "/throw 403 error" },
  22. { "foro.elhacker.net", "/throw_302_error" },
  23. { "www.google.es", "/" },
  24. { "foro.elhacker.net", "/ingenieria_inversa-b26.0/" }
  25. };
  26.  
  27.  
  28. hostent * host;
  29. in_addr ip;
  30. sockaddr_in data;
  31. string request;
  32.  
  33. for (int i = 0; i < links.size(); i++){
  34. host = gethostbyname(links[i][0].c_str());
  35. ip.s_addr = *(long * )host->h_addr_list[0];
  36.  
  37.  
  38. SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  39. if (sock == INVALID_SOCKET){
  40. cout << "Invalid socket";
  41. return 1;
  42. }
  43.  
  44. memset(&data, 0, sizeof(sockaddr_in));
  45. data.sin_addr = ip;
  46. data.sin_family = AF_INET;
  47. data.sin_port = htons(80);
  48.  
  49. if(connect(sock, (sockaddr*)&data, sizeof(sockaddr_in))){
  50. cout << "Connection with " << inet_ntoa(ip) << " failed.";
  51. return 1;
  52. }
  53.  
  54.  
  55. request = "GET " + links[i][1] + " HTTP/1.0\r\n";
  56. request += "Host: " + links[i][0] + "\r\n";
  57. request += "\r\n";
  58.  
  59. if (send(sock, request.c_str(), request.size(), 0) != request.size()){
  60. cout << "Send error";
  61. return 1;
  62. }
  63.  
  64. //Accept
  65. char buffer[SIZE];
  66. int lastBytes = SIZE - 1;//bytes recerved
  67. string response;
  68. while (lastBytes > 0){
  69. lastBytes = recv(sock, buffer, sizeof(buffer), 0);
  70. if (lastBytes > 0)
  71. response += string(buffer).substr(0, lastBytes);
  72. }
  73. string header = response.substr(0, response.find("\r\n\r\n") + 4);
  74.  
  75. HTTP http(header);
  76. //    or
  77. //http.setup(header);
  78. cout << "Host: " << links[i][0] << endl;
  79. cout << "HTTP version: " << http.HTTPVersion() << endl;
  80. if (http.Code() == H_Not_Found){
  81. cout << "Path: " << links[i][1] << " wasn't founded";
  82. }
  83. else if (http.Code() == H_Forbidden){
  84. cout << "Server Forbidden message";
  85. if (http.Other("Location").size() > 0){//Location field
  86. cout << " to " << http.Other("Location");
  87. }
  88. }
  89. else{
  90. cout << "Status code: " << http.Code();
  91. }
  92. cout << "\n\nAll fields: \n";
  93. for (int i = 0; i < http.Size(); i++){
  94. cout << http.Other(i)[0] << ": " << http.Other(i)[1] << endl;
  95. }
  96. cout << endl << endl;
  97.  
  98. }
  99.  
  100.  
  101. fflush(stdin);
  102. getchar();
  103. return 0;
  104. }

Descargar ejemplo: http://pruebasdephp.hol.es/things/HTTP_class.rar
Probado en visual studio 2013



Si me pueden dar ideas de que puedo mejorar o si tienen alguna duda  :D

Saludos


« Última modificación: 26 Diciembre 2014, 18:11 pm por patilanz » En línea

ivancea96


Desconectado Desconectado

Mensajes: 3.412


ASMático


Ver Perfil WWW
Re: Mi clase HTTP + winsock peticion HTTP ejemplo
« Respuesta #1 en: 26 Diciembre 2014, 18:13 pm »

Ahora haz para que todo el proceso de winsock lo lleve la clase (u otra clase/función aparte)

En vez de define, tal vez te interesa más hacer un enum :o


En línea

patilanz


Desconectado Desconectado

Mensajes: 481

555-555-0199@example.com


Ver Perfil WWW
Re: Mi clase HTTP + winsock peticion HTTP ejemplo
« Respuesta #2 en: 27 Diciembre 2014, 20:45 pm »

Hola gracias por tu respuesta. Ya creo que tengo lo que me dijiste.

http_class.cpp
Código
  1. //HTTP_class v2.0
  2. //Autor: patilanz
  3.  
  4. #ifndef HTTP_CLASS_HPP
  5. #define HTTP_CLASS_HPP
  6.  
  7. #include <string>
  8. #include <ctime>
  9. #include <vector>
  10. #include "http_config.hpp"
  11.  
  12. using namespace std;
  13.  
  14.  
  15. //CLASS STATE
  16. enum class_state{ SETUP_OK, SETUP_NEED, INVALID_HEADER, INVALID_URL, SOCK_ERROR, CONNECTION_TIME_OUT, CONNECTION_REFUSED, UNKNOW_ERROR, SEND_ERROR, INVALID_RESPONSE };
  17.  
  18. //HTTP CODES
  19.  
  20. //Informational
  21. #define H_Continue 100
  22. #define H_Switching_Protocols 101
  23. #define H_Processing 102
  24. //... no lo pongo para no ocupar espacio en el foro. Es como antes
  25.  
  26.  
  27.  
  28. class HTTP{
  29. public:
  30. HTTP();
  31. HTTP(string url, string request = "", int port = 80);
  32. HTTP(string url, HTTP_config config, int port = 80);
  33.  
  34. bool get(string url, string request = "", int port = 80);
  35. bool get(string url, HTTP_config config, int port = 80);
  36. bool get(string request = "", int port = 80);
  37.  
  38. bool setHeader(string header);
  39. void setContent(string content);
  40. bool setUrl(string url);
  41.  
  42. const int State();//class status
  43.  
  44. string Header();
  45. string Content();
  46.  
  47. int Code();//HTTP status
  48. tm Date();
  49. string Server();
  50. tm Last_Modified();
  51. string ETag();
  52. string Content_Type();
  53. int Content_Lenght();
  54. string Connection();
  55.  
  56. string getHost();
  57. string getPath();
  58. string getUrl();
  59.  
  60.  
  61.  
  62. string Other(string name);
  63. vector<string> Other(int i);
  64.  
  65. //helpful functions
  66. double HTTPVersion();
  67. int Size();//Size of fields
  68.  
  69.  
  70. private:
  71. int state;//Already setup?
  72.  
  73. int code;
  74. tm date;
  75. string server;
  76. tm last_modified;
  77. string etag;
  78. string content_type;
  79. int content_length;
  80. string connection;
  81. double version;
  82.  
  83. string host;
  84. string path;
  85. string url;
  86.  
  87. string header;
  88. string content;
  89.  
  90. vector < vector<string> > all; //all fields
  91.  
  92. const int recv_size = 1024;
  93.  
  94.  
  95. //helpful functions
  96. void WSAStart();
  97. vector<string> split(string full, string part);
  98.  
  99. //Config functions
  100. tm getDate(string date);
  101. void defaultConfig();
  102. };
  103.  
  104.  
  105.  
  106. #endif

http_class.cpp
Código
  1. #include "http_class.hpp"
  2. #include <regex>
  3. #include <WinSock2.h>
  4.  
  5. HTTP::HTTP(){
  6. defaultConfig();
  7. }
  8.  
  9. HTTP::HTTP(string url, string request, int port){
  10. defaultConfig();
  11. get(url, request, port);
  12. }
  13.  
  14. HTTP::HTTP(string url, HTTP_config config, int port){
  15. get(url, config, port);
  16. }
  17.  
  18.  
  19.  
  20.  
  21. string HTTP::Other(string name){
  22. for (int i = 0; i < all.size(); i++){
  23. if (all[i][0] == name){
  24. return all[i][1];
  25. }
  26. }
  27. return "";
  28. }
  29. vector<string> HTTP::Other(int i){
  30. if (i < all.size())
  31. return all[i];
  32. else
  33. return vector<string>();
  34. }
  35.  
  36.  
  37. bool HTTP::get(string _url, string _request, int port){
  38. smatch match;
  39. if (regex_search(_url, match, regex("(http|https)?:?(\\/\\/)?([^/]{5,})([^\\t\\n\\v\\r]*)"))){
  40. url = _url;
  41. host = match[3];
  42. path = match[4];
  43. if (path.size() < 1)
  44. path = "/";
  45.  
  46. hostent * _host;
  47. in_addr ip;
  48. sockaddr_in data;
  49. string request;
  50.  
  51.  
  52. _host = gethostbyname(host.c_str());
  53. ip.s_addr = *(long*)_host->h_addr_list[0];
  54.  
  55. SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  56. if (sock == INVALID_SOCKET){
  57. state = SOCK_ERROR;
  58. return false;
  59. }
  60. memset(&data, 0, sizeof(sockaddr_in));
  61. data.sin_addr = ip;
  62. data.sin_family = AF_INET;
  63. data.sin_port = htons(port);
  64.  
  65. if (connect(sock, (sockaddr*)&data, sizeof(sockaddr_in))){
  66. if (WSAGetLastError() == WSAETIMEDOUT){
  67. state = CONNECTION_TIME_OUT;
  68. }
  69. else if (WSAGetLastError() == WSAECONNREFUSED){
  70. state = CONNECTION_REFUSED;
  71. }
  72. else{
  73. state = UNKNOW_ERROR;
  74. }
  75. return false;
  76. }
  77. if (_request.size() > 0)
  78. request = _request;
  79. else{
  80. request += "GET " + path + " HTTP/1.1\r\n";
  81. request += "Host: " + host + "\r\n";
  82. request += "Connection: close\r\n";
  83. request += "\r\n";
  84. }
  85. if(send(sock, request.c_str(), request.size(), 0) != request.size()){
  86. state = SEND_ERROR;
  87. return false;
  88. }
  89. //Accept
  90. char *buffer = new char[recv_size]; // No se me ocurrio otra manera de usar una variable const int de la clase
  91. int lastBytes = recv_size - 1;
  92. string response;
  93.  
  94. while (lastBytes > 0){
  95. lastBytes = recv(sock, buffer, recv_size, 0);
  96. if (lastBytes > 0)
  97. response += string(buffer).substr(0, lastBytes);
  98. }
  99. if (response.find("\r\n\r\n") == -1){
  100. state = INVALID_RESPONSE;
  101. return false;
  102. }
  103. setHeader(response.substr(0, response.find("\r\n\r\n") + 4));
  104. setContent(response.substr(response.find("\r\n\r\n") + 4, response.size()));
  105.  
  106.  
  107.  
  108.  
  109.  
  110. delete[recv_size] buffer;
  111. return true;
  112.  
  113. }else{
  114. state = INVALID_URL;
  115. return false;
  116. }
  117. }
  118.  
  119. bool HTTP::get(string url,HTTP_config config, int port){
  120. setUrl(url);
  121. string request = config.getGet() + "\r\n";
  122. for (int i = 0; i < config.size(); i++){
  123. request += config[i][0] + ": " + config[i][1] + "\r\n";
  124. }
  125. request += "\r\n";
  126. return get(request, port);
  127. }
  128.  
  129. bool HTTP::get(string request, int port){
  130. return get(url, request, port);
  131. }
  132.  
  133.  
  134.  
  135. bool HTTP::setHeader(string _header){
  136. vector<string> parts = split(_header, "\r\n");
  137.  
  138. //all setup
  139. for (int i = 1; i < parts.size(); i++){
  140. all.push_back(split(parts[i],": " ));
  141. }
  142. all.pop_back();          // remove last 2 \r\n of the end of http protocol
  143. all.pop_back();          //
  144. //end
  145. if (all.size() < 1){ //Nothing founded
  146. state = INVALID_HEADER;
  147. return false;
  148. }
  149. header = _header;
  150.  
  151.  
  152. //http setup
  153. string v = parts[0].substr(5, 3);
  154. version = atof(v.c_str());
  155. code = atoi(parts[0].substr(8, 4).c_str());
  156. //end
  157. date = getDate(Other("Date"));
  158. server = Other("Server");
  159. last_modified = getDate(Other("Last-Modified"));
  160. etag = Other("ETag");
  161. content_type = Other("Content-Type");//Mejores en 2.0
  162. content_length = atoi(Other("Content-Length").c_str());
  163. connection = Other("Connection");
  164. state = SETUP_OK;
  165. return true;
  166. }
  167.  
  168. void HTTP::setContent(string c){
  169. content = c;
  170. }
  171.  
  172. bool HTTP::setUrl(string _url){
  173. if (regex_match(_url, regex("(http|https)?:?(\\/\\/)?([^/]{5,})([^\\t\\n\\v\\r]*)"))){
  174. url = _url;
  175. return true;
  176. }
  177. return false;
  178. }
  179.  
  180. int HTTP::Code(){
  181. return code;
  182. }
  183.  
  184. const int HTTP::State(){
  185. return state;
  186. }
  187.  
  188. tm HTTP::Date(){
  189. //Example of check
  190. if (date.tm_year != 0 && state == SETUP_OK){ // if == 0 no date in header
  191. return date;
  192. }
  193. }
  194. string HTTP::Server(){
  195. return server;
  196. }
  197. tm HTTP::Last_Modified(){
  198. return last_modified;
  199. }
  200. string HTTP::ETag(){
  201. return etag;
  202. }
  203. string HTTP::Content_Type(){
  204. return content_type;
  205. }
  206. int HTTP::Content_Lenght(){
  207. return content_length;
  208. }
  209. string HTTP::Connection(){
  210. return connection;
  211. }
  212.  
  213.  
  214. //Gets
  215.  
  216. string HTTP::getHost(){
  217. return host;
  218. }
  219. string HTTP::getPath(){
  220. return path;
  221. }
  222. string HTTP::getUrl(){
  223. return url;
  224. }
  225.  
  226.  
  227. string HTTP::Header(){
  228. return header;
  229. }
  230. string HTTP::Content(){
  231. return content;
  232. }
  233.  
  234.  
  235.  
  236. //Helpful functions
  237. double HTTP::HTTPVersion(){
  238. return version;
  239. }
  240. int HTTP::Size(){
  241. return all.size();
  242. }
  243.  
  244.  
  245.  
  246.  
  247.  
  248. tm HTTP::getDate(string _date){ //Get date in tm format for example in Date or Last-Modified
  249. tm date = tm();
  250. if (_date.size() > 0){
  251. const static string months[] = {
  252. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  253. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  254. };
  255. smatch match;
  256. if (_date.find("GMT") != -1){ // New format
  257. if (regex_search(_date, match, regex("^\\w{3,9},\\s(\\d{2})[\\s\\-](\\w{3})[\\s\\-](\\d{2,4})\\s(\\d{2}):(\\d{2}):(\\d{2}) GMT$"))){
  258. date.tm_mday = atoi(match[1].str().c_str());
  259. int month;
  260. for (int i = 0; i < sizeof(months); i++){
  261. if (months[i] == match[2].str()){
  262. month = i;
  263. break;
  264. }
  265. }
  266. date.tm_mon = month;
  267. int year = atoi(match[3].str().c_str());
  268. if (year > 1900)
  269. year -= 1900;
  270. date.tm_year = year;
  271. date.tm_hour = atoi(match[4].str().c_str());
  272. date.tm_min = atoi(match[5].str().c_str());
  273. date.tm_sec = atoi(match[6].str().c_str());
  274. }
  275. }
  276. else{ //Old ANSI format
  277. if (regex_search(_date, match, regex("^\\w{3} (\\w{3})  (\\d{1,2}) (\\d{2}):(\\d{2}):(\\d{2}) (\\d{4})$"))){
  278. int month;
  279. for (int i = 0; i < sizeof(months); i++){
  280. if (months[i] == match[1].str()){
  281. month = i;
  282. break;
  283. }
  284. }
  285. date.tm_mday = atoi(match[2].str().c_str());
  286. date.tm_hour = atoi(match[3].str().c_str());
  287. date.tm_min = atoi(match[4].str().c_str());
  288. date.tm_sec = atoi(match[5].str().c_str());
  289. date.tm_year = atoi(match[6].str().c_str());
  290. }
  291. }
  292. }
  293. return date;
  294. }
  295.  
  296.  
  297. void HTTP::defaultConfig(){ //Set some values help to don't check state in every function
  298. WSAStart();
  299. state = SETUP_NEED;
  300. code = 0;
  301. version = 0;
  302. content_length = 0;
  303.  
  304. }
  305.  
  306.  
  307.  
  308. void HTTP::WSAStart(){
  309. if (socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) == INVALID_SOCKET && WSAGetLastError() == WSANOTINITIALISED){
  310. WSADATA wsadata;
  311. WSAStartup(MAKEWORD(2, 2), &wsadata);
  312. }
  313. }
  314.  
  315.  
  316.  
  317.  
  318.  
  319.  
  320.  
  321.  
  322. //split string in vector
  323.  
  324. vector<string> HTTP::split(string full, string part){
  325. vector<string> parts;
  326. int last = 0;
  327. int p;
  328. while ((p = full.find(part, last)) != -1){
  329. parts.push_back(full.substr(last, p - last));
  330. last = p + part.size();
  331. }
  332. parts.push_back(full.substr(last, full.size()));
  333. return parts;
  334. }


http_config.hpp
Código
  1. #ifndef HTTP_CONFIG_HPP
  2. #define HTTP_CONFIG_HPP
  3.  
  4. #include <string>
  5. #include <vector>
  6. using namespace std;
  7.  
  8. class HTTP_config{
  9. public:
  10. HTTP_config();
  11. HTTP_config(string get);
  12. HTTP_config(string get, vector < vector <string > >);
  13. bool add(string name, string value);
  14. bool remove(string name);
  15. bool edit(string name, string value);
  16. const int size();
  17. void setGet(string);
  18. string getGet();
  19.  
  20. vector<string> operator [](const int);
  21. private:
  22. vector < vector<string> > data;
  23. string get;
  24. };
  25.  
  26.  
  27.  
  28. #endif

http_config.cpp
Código
  1. #include "http_config.hpp"
  2.  
  3. HTTP_config::HTTP_config(){}
  4. HTTP_config::HTTP_config(string _get){
  5. get = _get;
  6. }
  7. HTTP_config::HTTP_config(string _get, vector < vector<string> > _data){
  8. get = _get;
  9. data = _data;
  10. }
  11.  
  12.  
  13.  
  14. bool HTTP_config::add(string name, string value){
  15. for (int i = 0; i < data.size(); i++){
  16. if (data[i][0] == name)
  17. return false;
  18. }
  19. vector < string > a = {
  20. name, value
  21. };
  22. data.push_back(a);
  23. return true;
  24. }
  25. bool HTTP_config::remove(string name){
  26. for (int i = 0; i < data.size(); i++){
  27. if (data[i][0] == name){
  28. data.erase(data.begin() + i);
  29. return true;
  30. }
  31. }
  32. return false;
  33. }
  34. bool HTTP_config::edit(string name, string value){
  35. for (int i = 0; i < data.size(); i++){
  36. if (data[i][0] == name){
  37. data[i][1] = value;
  38. return true;
  39. }
  40. }
  41. return false;
  42. }
  43.  
  44. vector<string> HTTP_config::operator[](const int i){
  45. if (i < data.size()){
  46. return data[i];
  47. }
  48. else{
  49. return vector<string>();
  50. }
  51. }
  52.  
  53.  
  54. const int HTTP_config::size(){
  55. return data.size();
  56. }
  57.  
  58. string HTTP_config::getGet(){
  59. return get;
  60. }


main.cpp (Ejemplo)
Código
  1. #include <iostream>
  2. #include <WinSock2.h>
  3. #include <string>
  4. #include <vector>
  5. #include <regex>
  6. #include "http_class.hpp"
  7.  
  8. using namespace std;
  9.  
  10. #pragma comment(lib,"ws2_32.lib")
  11.  
  12. int main(){
  13. HTTP http;
  14. http.setUrl("http://foro.elhacker.net/programacion_cc/mi_clase_http_winsock_peticion_http_ejemplo-t427014.0.html");
  15. http.get();
  16. cout << http.Code() << endl << endl;
  17.  
  18.  
  19. HTTP http2("http://www.cplusplus.com/reference/");
  20. cout << http2.getHost() <<  ": HTTP/" << http2.HTTPVersion() << endl << endl;
  21.  
  22. HTTP_config config("GET / HTTP/1.0", {
  23. { "Host", "www.google.es" },
  24. { "Accept-Encoding", "gzip, deflate, sdch" },
  25. { "Accept-Language", "es,en;q=0.8" }
  26. });
  27. HTTP http3("www.google.es", config);
  28. cout << http3.Header();
  29. getchar();
  30. fflush(stdin);
  31.  
  32. HTTP http4("www.google.es", "", 21);
  33. if (http4.State() == CONNECTION_TIME_OUT){
  34. cout << "No answer from " << http4.getHost();
  35. }
  36. getchar();
  37. return 0;
  38. }

Descarga: http://pruebasdephp.hol.es/things/HTTP_class%20V2.0.rar


Cambie solo los class state por enums porque los otros eran muchos y no me apetece estar escribiendo uno a uno y mirar todos los números otra vez.


Algún fallo o recomendación ? Esta bien hecha?
En línea

ivancea96


Desconectado Desconectado

Mensajes: 3.412


ASMático


Ver Perfil WWW
Re: Mi clase HTTP + winsock peticion HTTP ejemplo
« Respuesta #3 en: 28 Diciembre 2014, 00:30 am »

Sobre el envío, ten en cuenta el envío Chuncked :O
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Como enviar una peticion HTTP desde winsock
Programación Visual Basic
illuminat3d 1 2,599 Último mensaje 5 Enero 2009, 01:07 am
por Karcrack
Ejemplo hacking metodo put http
Nivel Web
delorean 2 6,823 Último mensaje 19 Febrero 2011, 19:01 pm
por delorean
Peticion HTTP por proxy
Hacking
TomaSs 2 4,956 Último mensaje 23 Junio 2011, 07:36 am
por TomaSs
Peticion HTTP desde servidor remoto
Programación General
TomaSs 0 3,124 Último mensaje 7 Junio 2011, 03:51 am
por TomaSs
Petición HTTP en C++ mediante sockets?
Programación C/C++
Puntoinfinito 5 5,556 Último mensaje 19 Marzo 2013, 16:45 pm
por 0xDani
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines