/home/hylent/cpp/socket/login.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <cstring> // memset
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h> // in_addr
#include <netdb.h> // hostent
using namespace std;
const int HostPort = 80;
const char *HttpReqFormat = "POST %s HTTP/1.1\n"
"Accept: */*\n"
"Accept-Language: zh-cn\n"
"host: %s\n"
"Content-Type: application/x-www-form-urlencoded\n"
"Content-Length: %d\n"
"Connection: close\n"
"\n"
"%s";
int main(int argc, char **argv)
{
if (argc < 2)
{
cout << "error: no cfg file" << endl;
return -1;
}
ifstream ifs(argv[1]);
if (!ifs.is_open())
{
cout << "error: cannot read file " << argv[1] << endl;
return -1;
}
char hostStr[20];
ifs.getline(hostStr, 20);
char hostUri[50];
ifs.getline(hostUri, 50);
string data;
char dataBuf[50];
int i = 0;
while (!ifs.eof() && ++i < 10)
{
ifs.getline(dataBuf, 50);
data += dataBuf;
data += (i % 2) ? '=' : '&';
}
struct hostent *h1 = gethostbyname(hostStr);
if (h1 == NULL)
{
cout << "error: host invalid" << endl;
return -1;
}
int s1 = socket(AF_INET, SOCK_STREAM, 0);
if (s1 < 0)
{
cout << "error: cannot create socket" << endl;
return -1;
}
struct sockaddr_in a1;
a1.sin_family = AF_INET;
a1.sin_port = htons(HostPort);
a1.sin_addr = *((struct in_addr*) h1->h_addr);
memset(&(a1.sin_zero), 0, 8);
int c1 = connect(s1, (struct sockaddr*) &a1, sizeof(struct sockaddr));
if (c1 < 0)
{
cout << "error: cannot connect" << endl;
return -1;
}
char reqBuf[1024];
sprintf(reqBuf, HttpReqFormat, hostUri, hostStr, data.size(), data.c_str());
send(s1, reqBuf, strlen(reqBuf), 0);
char buf[1024];
int r1 = recv(s1, buf, 1023, 0);
buf[r1] = '\0';
cout << buf << endl;
close(s1);
return 0;
}
/home/hylent/cpp/socket/login.data
localhost
/t/f/login.php
user
hylent
pass
icannottellyou
/var/www/t/f/login.php
<?php
print_r($_POST);
output
g++ login.cpp -o login
./login login.data
HTTP/1.1 200 OK
Date: Sat, 05 Nov 2011 12:34:45 GMT
Server: Apache/2.2.20 (Ubuntu)
X-Powered-By: PHP/5.3.6-13ubuntu3.2
Vary: Accept-Encoding
Content-Length: 60
Connection: close
Content-Type: text/html; charset=UTF-8
Array
(
[user] => hylent
[pass] => icannottellyou
)