mazinsw
(usa Ubuntu)
Enviado em 03/04/2010 - 23:08h
consegui(mais ainda não consigo baixar um arquivo)!
o código pro pessoal:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
char * post_http_method(const char * URL, const char * params)
{
char host[256] = "";
char page[256] = "";
char request[2049] = "";
int port = 80;
struct sockaddr_in skaddr;
struct hostent *hent;
sscanf(URL, "http://%99[^/]/%99[^\n]", host, page);
hent = gethostbyname(host);
if (hent == NULL)
{
int new_port = 0;
char ip[64] = "";
sscanf(host, "%99[^:]:%d", ip, &new_port);
if (!new_port == 0 || !strlen(ip) > 0)
{
port = new_port;
sprintf(host, "%s", ip);
}
if( inet_pton(AF_INET,host,&skaddr.sin_addr) < 0)
{
return NULL;
}
}
else
{
memcpy(&skaddr.sin_addr, hent->h_addr, hent->h_length);
}
sprintf(request, "POST /%s HTTP/1.1\r\n", page);
sprintf(request, "%sHost: %s\r\n", request, host);
strcat(request, "Content-Type: application/x-www-form-urlencoded\r\n");
sprintf(request, "%sContent-Length: %d\r\n", request, strlen(params));
sprintf(request, "%s\r\n%s\r\n", request, params);
int mysocket;
if ((mysocket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
return NULL;
}
int flagtnd = 1;
setsockopt(mysocket, IPPROTO_TCP, 1, (char *) &flagtnd, sizeof(int));
struct timeval tv;
tv.tv_sec = 3;
tv.tv_usec = 0;
setsockopt(mysocket, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof tv);
skaddr.sin_family = AF_INET;
skaddr.sin_port = htons(port);
if(connect(mysocket, (struct sockaddr *) &skaddr, sizeof(struct sockaddr)) < 0)
{
return NULL;
}
if( (send(mysocket, request, strlen(request), 0)) < 0)
{
close(mysocket);
return NULL;
}
char buffer[1024];
char * data = (char *) malloc(sizeof(char) * 1024);
int count;
while ((count = recv(mysocket, buffer, 1024, 0)) > 0)
{
buffer[count] = 0;
data = realloc(data, strlen(data) + 1024);
strcat(data, buffer);
memset(buffer,'{TEXTO}',1024);
}
close(mysocket);
return data;
}