InternetReadFile get specificity line - c++

i need help about getting a fist line from a web page, found a little script working with ipchicken.com.
but i connot run it with me web script , posting the original code becouse i was mad about all things ... for that!
i search for that here but i dont find and i post a question ..
but it need to be edit correctly to works with mine php script ..
php > file.php?get=ver or ip on 192.168.1.1 port 88
switch($_GET['get'])
{
case "ip" :
echo ($_SERVER['REMOTE_ADDR']);
break;
case "ver" :
print "0.1.1";
break;
default :
break;
}
here is the original c++ code >
char *getwebpage(char *hostname, char *uri, unsigned long *total)
{
if(!hostname || !uri || !total) return (char *)0;
*total = 0;
char *headers1 = "Accept: text/html, */*\nAccept-Language: en-GB\nAccept-Encoding: none\nHost: ";
char *headers2 = (char *)malloc(strlen(headers1) + strlen(hostname) + 2);
sprintf(headers2, "%s%s\n", headers1, hostname);
HINTERNET session = InternetOpen("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
HINTERNET connect = InternetConnect(session, hostname, 80, "", "", INTERNET_SERVICE_HTTP, 0, 0);
HINTERNET http = HttpOpenRequest(connect, "GET", uri, HTTP_VERSION, NULL, 0, INTERNET_FLAG_DONT_CACHE, 0);
HttpSendRequest(http, headers2, strlen(headers2), NULL, 0);
free(headers2);
unsigned long read;
char buffer[1024];
char *final = (char *)malloc(1024);
memset(buffer, 0, 1024);
while(InternetReadFile(http, buffer, 1024, &read) && (read != 0)){
CopyMemory((final + *total), buffer, read);
*total += read;
final = (char *)realloc(final, (*total + 1024));
memset((final + *total), 0, 1024);
}
InternetCloseHandle(http);
InternetCloseHandle(connect);
InternetCloseHandle(session);
return final;
}
int getmyipaddress(char *buffer)
{
unsigned long length;
char *webpage = getwebpage("www.ipchicken.com", "/", &length);
if(!webpage || length == 0) return 0;
int result = 0;
char *start = strstr(webpage, "<b>");
if(start){
start += 3;
while(*start <= ' ') start++;
char *end = start;
while(*end > ' ') end++;
*end = 0;
strcpy(buffer, start);
result = 1;
}
free(webpage);
return result;
}
and .. yea how to add a port select like this ->
char *getwebpage(char *hostname, char *uri, char *port, unsigned long *total)
HINTERNET connect = InternetConnect(session, hostname, port, "", "", INTERNET_SERVICE_HTTP, 0, 0);

You say your service is at port 88, but you call:
HINTERNET connect = InternetConnect(session, hostname, 80, ....
so maybe change to:
HINTERNET connect = InternetConnect(session, hostname, 88, ....

Try to do InternetReadFile(http, &buffer, 1024, &read). I am not sure if this will sove your problem but I am quite sure there has to be a pointer to the buffer in the function InternetReadFile() call

Related

how to fix that C++ ImGui key system isnt working?

i am coding at an key authentication system with imgui. I use the Download String function to get the key. But the if says that the user input and the downloaded key are not the same.
this is the DownloadString function:
std::string DownloadString(std::string URL) {
HINTERNET interwebs = InternetOpenA("Mozilla/5.0", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, NULL);
HINTERNET urlFile;
std::string rtn;
if (interwebs) {
urlFile = InternetOpenUrlA(interwebs, URL.c_str(), NULL, NULL, NULL, NULL);
if (urlFile) {
char buffer[2000];
DWORD bytesRead;
do {
InternetReadFile(urlFile, buffer, 2000, &bytesRead);
rtn.append(buffer, bytesRead);
memset(buffer, 0, 2000);
} while (bytesRead);
InternetCloseHandle(interwebs);
InternetCloseHandle(urlFile);
std::string p = replaceAll(rtn, "|n", "\r\n");
return p;
}
}
InternetCloseHandle(interwebs);
std::string p = replaceAll(rtn, "|n", "\r\n");
return p;
}
and this is my code:
std::string key = DownloadString("https://pastebin.com/raw/sGjce0HG");
char buf[500]{"Your key here"};
ImGui::InputText("", buf, 500);
std::string user_key = buf;
if (user_key == key)
{
ImGui::Text("key is working");
}
i hope you can help me

HTTP POST request via Wininet

In VC++, I am trying to send an HTTP POST request and get its response.
I have the below code, which compiles successfully, yet fails to POST.
First I try to send the POST request to the request bin for testing purpose
int main(int argc, _TCHAR* argv[])
{
static CHAR hdrs[] = "Content-Type: application/x-www-form-urlencoded";
static CHAR frmdata[] = "name=John+Doe&userid=hithere&other=P%26Q";
HINTERNET hSession = InternetOpenA("MyAgent", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
HINTERNET hConnect = InternetConnect(hSession "pipedream.com", 8733, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
HINTERNET hRequest = HttpOpenRequestA(hConnect, "POST", "/r/enj77inn26shk", NULL, NULL, NULL, 0, 1);
HttpSendRequestA(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));
Then read the response using
DWORD dwContentLen;
DWORD dwBufLen = sizeof(dwContentLen);
if (HttpQueryInfo(hRequest,
HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
(LPVOID)&dwContentLen,
&dwBufLen,
0))
{
char *pData = (char*)GlobalAlloc(GMEM_FIXED, dwContentLen + 1);
DWORD dwReadSize = dwContentLen / 10; // We will read 10% of data
// with each read.
DWORD cReadCount;
DWORD dwBytesRead;
char *pCopyPtr = pData;
for (cReadCount = 0; cReadCount < 10; cReadCount++)
{
InternetReadFile(hRequest, pCopyPtr, dwReadSize, &dwBytesRead);
pCopyPtr = pCopyPtr + dwBytesRead;
}
// extra read to account for integer division round off
InternetReadFile(hRequest,
pCopyPtr,
dwContentLen - (pCopyPtr - pData),
&dwBytesRead);
// Null terminate data
pData[dwContentLen] = 0;
std::cout << pData << std::endl;
system("pause");
}
return 0;
}
The endpoint I'm posting to

mongoose web response delay

I am new to mongoose web server. I am developing a simple http server which returning a image in response, everything works fine. But when requesting from browser, irrespect to the file size, it takes exactly 1000 milliseconds to reach the web server event handler.
Is there any configuration to change this delay.
static const char *s_http_port = "8089";
static struct mg_serve_http_opts s_http_serve_opts;
static void send_file(struct mg_connection *nc){
char buf[1024];
int n;
FILE *fp;
const char *file_path = "C:\\sample.jpg";
fp = fopen(file_path, "rb");
if(fp == NULL){
printf("Error, file %s not found.", file_path);
}
char *mimeType = "image/jpg";
fseek(fp, 0L, SEEK_END);
long sz = ftell(fp) + 2;
fseek(fp, 0L, SEEK_SET);
mg_printf(nc,
"HTTP/1.1 200 OK\r\n"
"Cache: no-cache\r\n"
"Content-Type: %s\r\n"
"Content-Length: %d\r\n"
"\r\n",
mimeType,
sz);
while((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
mg_send(nc, buf, n);
}
fclose(fp);
mg_send(nc, "\r\n", 2);
nc->flags |= MG_F_SEND_AND_CLOSE;
}
static void ev_handler(struct mg_connection *nc, int ev, void *ev_data){
struct http_message *hm = (struct http_message *)ev_data;
switch(ev)
{
case MG_EV_HTTP_REQUEST:
{
if(mg_vcmp(&hm->uri, "/hello") == 0){
handle_recv(nc);
} else if(mg_vcmp(&hm->uri, "/img") == 0){
send_file(nc);
} else {
mg_serve_http(nc, (struct http_message *) ev_data, s_http_serve_opts);
}
}
break;
case MG_EV_RECV:
break;
case MG_EV_CLOSE:
break;
}
}
int main(void)
{
struct mg_mgr mgr;
struct mg_connection *nc;
mg_mgr_init(&mgr, NULL);
nc = mg_bind(&mgr, s_http_port, ev_handler);
mg_set_protocol_http_websocket(nc);
s_http_serve_opts.document_root = "./images";
s_http_serve_opts.dav_document_root = "./images";
s_http_serve_opts.enable_directory_listing = "yes";
printf("Starting web server on port %s\n", s_http_port);
for(;;) {
mg_mgr_poll(&mgr, 500);
}
mg_mgr_free(&mgr);
return 0;
}

C++ variable gotten from GETTEXT as a mysql_query variable

I'm trying to do the following:
get username typed into the userField
make a SEARCH mysql_query with the username as a variable
I'm having a hard time getting past phase 2 since mysql_query takes a const char* as the query string, and I can only get username as char* or wchar_t*
I'm also compiling in unicode.
My code for now:
void mysql_connect(HWND hLoginWnd) {
MYSQL *con, mysql;
MYSQL_RES *res;
mysql_init(&mysql);
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "utf8");
mysql_real_connect(&mysql, "localhost", "root", "", "treenitaulu", 3306, NULL, 0);
char name[512], pass[512];
int lenUser = SendMessage(userField, WM_GETTEXT, 512, (LPARAM)name);
int lenPass = SendMessage(passField, WM_GETTEXT, 512, (LPARAM)pass);
if(lenUser > 0 && lenPass > 0) {
std::string query = "SELECT pass FROM users WHERE name='" + std::string(name) + "'";
mysql_query(&mysql, query.c_str());
}
}
What should I do?
You are setting the SQL charset to UTF-8, so use WideCharToMultiByte() to convert the retreived UI Unicode strings into UTF-8, then pass the converted data to the DB query. UTF-8 encoded data can be stored using char buffers, and you can pass a char* (or char[]) where a const char* is expected. For example:
std::string Utf8Encode(WCHAR *wStr, int wLen)
{
int utf8len = WideCharToMultiByte(CP_UTF8, 0, wStr, wLen, NULL, 0, NULL, NULL);
if (utf8len > 0)
{
std::vector<char> utf8(utf8len);
utf8len = WideCharToMultiByte(CP_UTF8, 0, wStr, wLen, &utf8[0], utf8len, NULL, NULL);
if (utf8len > 0)
return std::string(&utf8[0], utf8len);
}
return std::string();
}
void mysql_connect(HWND hLoginWnd)
{
MYSQL *con, mysql;
MYSQL_RES *res;
mysql_init(&mysql);
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "utf8");
mysql_real_connect(&mysql, "localhost", "root", "", "treenitaulu", 3306, NULL, 0);
WCHAR name[512];
int lenUser = SendMessage(userField, WM_GETTEXTW, 512, (LPARAM)name);
if (lenUser > 0)
{
std::string query = "SELECT pass FROM users WHERE name='" + Utf8Encode(name, lenUser) + "'";
mysql_query(&mysql, query.c_str());
...
}
}
With that said, you really need to escape strings when building SQL statements dynamically. It is safer as it is not prone to SQL Injection attacks:
std::string Utf8EncodeAndEscape(MYSQL *mysql, WCHAR *wStr, int wLen)
{
int utf8len = WideCharToMultiByte(CP_UTF8, 0, wStr, wLen, NULL, 0, NULL, NULL);
if (utf8len > 0)
{
std::vector<char> utf8(utf8len);
utf8len = WideCharToMultiByte(CP_UTF8, 0, wStr, wLen, &utf8[0], utf8len, NULL, NULL);
if (utf8len > 0)
{
std::vector<char> escaped(utf8len*2+1);
unsigned long escapedLen = mysql_real_escape_string(mysql, &escaped[0], &utf8[0], utf8len);
if (escapedLen > 0)
return std::string(&escaped[0], escapedLen);
}
}
return std::string();
}
void mysql_connect(HWND hLoginWnd)
{
MYSQL *con, mysql;
MYSQL_RES *res;
mysql_init(&mysql);
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "utf8");
mysql_real_connect(&mysql, "localhost", "root", "", "treenitaulu", 3306, NULL, 0);
WCHAR name[512];
int lenUser = SendMessage(userField, WM_GETTEXTW, 512, (LPARAM)name);
if (lenUser > 0)
{
std::string query = "SELECT pass FROM users WHERE name='" + Utf8EncodeAndEscape(&mysql, name, lenUser) + "'";
mysql_query(&mysql, query.c_str());
...
}
}
Parameterized queries would be just as safe, but are more efficient than dynamic SQL statements, especially if you need to execute the same statement multiple times:
std::wstring Utf8Decode(char *utf8Str, int utf8Len)
{
int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8Str, utf8Len, NULL, 0);
if (wLen > 0)
{
std::vector<wchar_t> wStr(wLen);
wLen = MultiByteToWideChar(CP_UTF8, 0, utf8Str, utf8Len, &wStr[0], wLen);
if (wLen > 0)
return std::wstring(&wStr[0], wLen);
}
return std::wstring();
}
MYSQL_STMT *stmt = mysql_stmt_init(&mysql);
if (stmt)
{
std::string query = "SELECT pass FROM users WHERE name=?"
if (mysql_stmt_prepare(stmt, query.c_str(), query.length()) == 0)
{
if (mysql_stmt_param_count(stmt) == 1)
{
std::string utf8User = Utf8Encode(name, lenUser);
unsigned long utf8len = utf8User.length();
MYSQL_BIND param = {0};
param.buffer_type = MYSQL_TYPE_STRING;
param.buffer = utf8User.c_str();
param.buffer_length = utf8len;
param.length = &utf8len;
param.is_unsigned = true;
mysql_stmt_bind_param(stmt, &param);
char result[512];
unsigned long resultLen = 0;
MYSQL_BIND result = {0};
param.buffer_type = MYSQL_TYPE_STRING;
param.buffer = &result[0];
param.buffer_length = 512;
param.length = &resultlen;
param.is_unsigned = true;
mysql_stmt_bind_result(stmt, &result);
if (mysql_stmt_execute(stmt) == 0)
{
mysql_stmt_fetch(stmt);
mysql_stmt_free_result(stmt);
SendMessage(passField, WM_SETTEXTW, 0, (LPARAM) Utf8Decode(result, resultLen).c_str());
}
}
}
}
mysql_stmt_close(stmt);

how to display info in a listbox instead of edit box?

i want to create a client server program in mfc
i found some really good source code from this website: http://www.softwareandfinance.com/Visual_CPP/TCP_Client_Server.html
ok can someone help me display the information in a listbox instead of the edit box?
here's the code to process the client:
static void f(void *p)
{
CSocketTestServerDlg *pDlg = reinterpret_cast<CSocketTestServerDlg*>(p);
pDlg->ProcessClientRequest();
}
void CSocketTestServerDlg::ProcessClientRequest()
{
SOCKADDR_IN clientaddr;
struct hostent *hostentry;
int len = sizeof(clientaddr);
SOCKET clientsocket = accept(m_serversocket, (sockaddr*)&clientaddr, &len);
if(len == -1)
{
AfxMessageBox("Error accpeting the client socket");
}
else
{
char *p = inet_ntoa(clientaddr.sin_addr);
int portno = ntohs(clientaddr.sin_port);
// int inet_pton(int af, const char *restrict src, void *restrict dst);
char rbuf[1024];
recv(clientsocket, rbuf, 1024, 0);
for(int i = 1024; i >= 1; i--)
{
if(rbuf[i] == '\n' && rbuf[i - 1] == '\r')
{
rbuf[i-1] = '\0';
break;
}
}
CString strRecvData;
strRecvData.Format("%s\r\n%s %d\r\n%s\r\n\r\n", (const char*)CTime::GetCurrentTime().Format("%B %d, %Y %H:%M:%S"), p, portno, rbuf);
m_recvData += strRecvData;
m_bRefershData = true;
strcat(rbuf, "\r\n");
send(clientsocket, rbuf, 1024, 0);
closesocket(clientsocket);
}
}
so how can i just get the ip address from the client to display in a list box? i don't need all the other information
Well, you already have the IP as a string in p, don't you?
You could create a CString from it to avoid UNICODE problems. Then use CListBox::AddString to output your string:
char *p = inet_ntoa(clientaddr.sin_addr);
CString str(p);
//CListBox listbox;
listbox.AddString(str);