Test Foro de elhacker.net SMF 2.1

Programación => Programación C/C++ => Mensaje iniciado por: Riki_89D en 4 Octubre 2011, 15:58 PM

Título: Cabecera HTTP + Winsock + strcat()
Publicado por: Riki_89D en 4 Octubre 2011, 15:58 PM
Hola que tal?

solo tengo una pequeña duda,quiro usar sockets para interacturr con webs,cosas como inicar sesion entre otras cosas,mi pregunta es si para enviar las acbeceras HTTP tengo k acer varias variables i ir concatenandolas con strcat() o hay alguna otra forma mas facil?¿



gracias
Título: Re: Cabecera HTTP + Winsock + strcat()
Publicado por: madpitbull_99 en 5 Octubre 2011, 15:12 PM
Los más sencillo sería utilizar alguna librería como libcurl (http://curl.haxx.se/libcurl/c/libcurl-tutorial.html), facilitan mucho las tareas.

Deberías leer también sobre CGI (http://www.cs.tut.fi/%7Ejkorpela/forms/cgic.html). Si estás en Windows puedes usar WinInet (http://support.microsoft.com/kb/165298).

Para un ejemplo básico de petición GET en la cabecera deberías incluir: GET /index.htm HTTP 1.1\r\n\n. Y en efecto, guardas el string en una variable,
abres un socket y envías el string almacenado anteriormente y luego capturas la respuesta.

Te dejo un ejemplo sacado del foro de MSDN (http://social.msdn.microsoft.com/Forums/en/vcgeneral/thread/982b5a5a-0c32-4cd1-a9fe-b66a5c71a3d8) que se loguea en MegaUpload desde C en Windows:

#include <winsock2.h>
#include <windows.h>
#include <string.h>
#include <stdio.h>


#pragma comment(lib,"ws2_32.lib")

#define HOST "www.megaupload.com
"
#define PORT 80

#define LEN 534 // Points to contenth length in http_req[]

int hconnect(char* host,int port);
int s=0;

char http_req[]=
"POST /?c=login HTTP/1.1\r\n"
"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, */* \r\n"
"Referer: http://megaupload.com/?c=login
\r\n"
"Accept-Language: en-US\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n"
"UA-CPU: x86\r\n"
"Accept-Encoding: gzip, deflate\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)\r\n"
"Host: megaupload.com\r\n"
"Content-Length: 00\r\n" // LEN points here!!!
"Connection: Keep-Alive\r\n"
"Cache-Control: no-cache\r\n\r\n";

char http_line_req[]="login=1&redir=1&username=usrname&password=pass\r\n\r\n"; // fill in here

char conn[1024];

int nLen=0;
char szLen[2];

void main()
{
nLen=strlen(http_line_req);
itoa(nLen,szLen,10);
memcpy(http_req+LEN,szLen,2);

s=hconnect(HOST,PORT);

send(s,http_req,strlen(http_req),NULL);
send(s,http_line_req,nLen,NULL);
recv(s,conn,1024,NULL);
//TODO: continue recv'ing, that 1KB buffer is not enough to recv all the data :)
}

int hconnect(char* host,int port)
{
WSAData wsa;
WSAStartup(MAKEWORD(1,1),&wsa);

struct sockaddr_in sai;
struct hostent *hp;

memset(&sai,0,sizeof(struct sockaddr_in));

hp=gethostbyname(host);

sai.sin_family=AF_INET;
sai.sin_addr=*((struct in_addr *)hp->h_addr);
sai.sin_port=htons(port);

SOCKET s;

s=socket(AF_INET,SOCK_STREAM,0);
connect(s,(struct sockaddr*)&sai,sizeof(sockaddr));
return s;
}

Título: Re: Cabecera HTTP + Winsock + strcat()
Publicado por: Riki_89D en 5 Octubre 2011, 18:59 PM
Hola que tal,ya use wininet,pero no me fue muy bien que digamos,ademas prefiero usar sockets o libcurl,gracias por el code,solo queria saber como almacenar esa variable


gracias

EI: ¿820 mensajes y todavia no sabes que no hay que hacer doble post?  :¬¬

Por cierto,cuando usaba wininet si iniciaba sesion (en este foro) pero a la hora de postear me decia que la sesion abia expirado,:S nunca llegue a soluciona ese maldito error,imagino que son las cookies,entones e estado observando las cabeceras de peticion cuando inicamos sesion aqui y hay una parametro "Cookie",debo incluirlo a la cabecera para que no pase eso?¿


gracias
Título: Re: Cabecera HTTP + Winsock + strcat()
Publicado por: madpitbull_99 en 5 Octubre 2011, 21:48 PM
Una vez iniciada la sesión deberías incluir la cookie en cada petición.

Es así como SMF comprueba que el que intenta postear una noticia/tema es realmente quien dice ser.

Título: Re: Cabecera HTTP + Winsock + strcat()
Publicado por: Riki_89D en 5 Octubre 2011, 21:50 PM
Perdona mi GRANDISIMA ignorancia ee,pero me surjen 2 preguntas....

1: La funcion a usar para agregar coockies es InternetSetCookie o HttpAddRequestHeader() ?,como agrego la cookie?

2: Hay alguna pagina donde explice como funcionan los foros como SMF o los demas tipos?¿



gracias por todo


ADJUNTO:

Es que tengo este codigo pero almenos con la funcion InternetSetCookie no funciona :S


Código (cpp) [Seleccionar]

Sesion = InternetOpen("Mozilla/5.0 (Windows NT 6.1; WOW64;rv:5.0.1)Gecko/20100101 Firefox/5.0.1",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,1);
Conexion = InternetConnect(Sesion,"foro.elhacker.net",INTERNET_DEFAULT_HTTP_PORT,NULL,NULL,INTERNET_SERVICE_HTTP,INTERNET_FLAG_NO_CACHE_WRITE,1);
Peticion = HttpOpenRequest(Conexion,"POST","/login2.html","HTTP/1.1",NULL,NULL,INTERNET_FLAG_NO_CACHE_WRITE,0);
InternetSetCookie("http://foro.elhacker.net",NULL,"TestData2 = Test; expires = Mon,10-Oct-2011 00:00:00 GMT");
HttpSendRequest(Peticion,Header,strlen(Header),Form,strlen(Form));
Peticion2 = HttpOpenRequest(Conexion,"POST","post2.html;start=0;board=49",NULL,NULL,NULL,INTERNET_FLAG_NO_CACHE_WRITE,0);
InternetSetCookie("http://foro.elhacker.net/post2.html;start=0;board=49",NULL,"TestData2 = Test; expires = Mon,10-Oct-2011 00:00:00 GMT");
HttpSendRequest(Peticion2,Header,strlen(Header),form2,strlen(form2));
   
Título: Re: Cabecera HTTP + Winsock + strcat()
Publicado por: madpitbull_99 en 6 Octubre 2011, 11:43 AM
No estoy muy puesto en C++, pero al enviar un post deberías incluir las siguientes campos en la cabecera HTTP:



Host: foro.elhacker.net
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Referer: http://foro.elhacker.net/redes-b4.0/
Cookie: __utma= <aqui va el código aleatorio de la cookie generado por el foro>
PHPSESSID=<el id de sesion generado por Apache/PHP>;


Ese es el modelo de como deberían ser las cabeceras que envíe tu aplicación.

Siento no poder ayudarte más.