Codice:
#include <iostream>
#include <WinSock2.h>
#include <string>
#pragma comment(lib, "ws2_32.lib")
std::string integer_to_string(int n)
{
static char buffer[32+1];
_itoa_s(n,buffer,32,10);
return std::string(buffer);
}
std::string GetHostByUrl(char *url)
{
struct hostent *Hostent = gethostbyname(url);
char Host[20];
sprintf (Host, "%d.%d.%d.%d",
(unsigned __int8)Hostent->h_addr_list[0][0],
(unsigned __int8)Hostent->h_addr_list[0][1],
(unsigned __int8)Hostent->h_addr_list[0][2],
(unsigned __int8)Hostent->h_addr_list[0][3]);
return Host;
}
SOCKADDR_IN post_addr(char *url)
{
SOCKADDR_IN post_addr;
post_addr.sin_family = AF_INET;
post_addr.sin_port = htons(80);
post_addr.sin_addr.s_addr = inet_addr(GetHostByUrl(url).c_str());
return post_addr;
}
void _SendHttpPostRequest(SOCKET sock, std::string str) { send(sock, str.c_str(), str.size(), 0); }
void SendHttpPostRequest(SOCKET sock, std::string url, std::string page, std::string data)
{
_SendHttpPostRequest(sock, "POST " + page + " HTTP/1.1\r\n");
_SendHttpPostRequest(sock, "Host: " + url + "\r\n");
_SendHttpPostRequest(sock, "User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1\r\n");
_SendHttpPostRequest(sock, "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n");
_SendHttpPostRequest(sock, "Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3\r\n");
_SendHttpPostRequest(sock, "Accept-Encoding: gzip, deflate\r\n");
_SendHttpPostRequest(sock, "Connection: keep-alive\r\n");
_SendHttpPostRequest(sock, "Referer: http://" + url + "/\r\n");
_SendHttpPostRequest(sock, "X-MailRuSputnik: generic\r\n");
_SendHttpPostRequest(sock, "Content-Type: application/x-www-form-urlencoded\r\n");
_SendHttpPostRequest(sock, "Content-Length: " + integer_to_string(data.size()) + "\r\n");
_SendHttpPostRequest(sock, "\r\n");
_SendHttpPostRequest(sock, data);
}
int main()
{
WSADATA wsa;
if(WSAStartup(MAKEWORD(2, 1), &wsa))
{
std::cout << "WSAStartup() error" << std::endl;
getchar();
return 1;
}
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN Post_addr = post_addr("www.extremedoor.org");
if(connect(sock, (SOCKADDR*)&Post_addr, sizeof(Post_addr)) == SOCKET_ERROR)
{
closesocket(sock);
std::cout << "connect() error" << std::endl;
getchar();
return INVALID_SOCKET;
}
SendHttpPostRequest(sock, "extremedoor.org", "/post_example.php", "key=123");
char response[4096 + 1];
recv(sock, response, 4096, 0);
response[strlen(response) - 1] = 0;
std::cout << response << std::endl;
getchar();
return 0;
}