Move HINTERNET connect outside the procedure - c++

This is a shortened version of my code:
#include <iostream>
#include <urlmon.h>
#include <wininet.h>
#pragma comment(lib, "urlmon.lib")
#pragma comment(lib, "wininet.lib")
void data();
void test(std::string received) {
data();
Sleep(1);
}
void data() {
- >>HINTERNET connect = InternetOpen(L"MyBrowser", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
HINTERNET OpenAddress = InternetOpenUrl(connect, L"web page", NULL, 0, INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_KEEP_CONNECTION, 0);
char dataReceived[5000];
std::string received;
DWORD NumberOfBytesRead = 0;
while (InternetReadFile(OpenAddress, dataReceived, 5000, &NumberOfBytesRead) && NumberOfBytesRead)
{
received += std::string(dataReceived);
}
- >>InternetCloseHandle(connect);
InternetCloseHandle(OpenAddress);
test(received);
}
int main() {
data();
}
Please tell me how to normally move the selected lines (- >>) outside the function to run them once?

Change data() and test() to take an HINTERNET as a parameter, and then main() can create the HINTERNET to pass in, eg:
#include <iostream>
#include <urlmon.h>
#include <wininet.h>
#pragma comment(lib, "urlmon.lib")
#pragma comment(lib, "wininet.lib")
void data(HINTERNET connect);
void test(HINTERNET connect, std::string received) {
data(connect);
Sleep(1);
}
void data(HINTERNET connect) {
HINTERNET OpenAddress = InternetOpenUrl(connect, L"web page", NULL, 0, INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_KEEP_CONNECTION, 0);
char dataReceived[5000];
std::string received;
DWORD NumberOfBytesRead = 0;
while (InternetReadFile(OpenAddress, dataReceived, 5000, &NumberOfBytesRead) && NumberOfBytesRead)
{
received += std::string(dataReceived);
}
InternetCloseHandle(OpenAddress);
test(connect, received);
}
int main() {
HINTERNET connect = InternetOpen(L"MyBrowser", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
data(connect);
InternetCloseHandle(connect);
}

Related

InternetOpenUrl Unhandled exception [duplicate]

This is a shortened version of my code:
#include <iostream>
#include <urlmon.h>
#include <wininet.h>
#pragma comment(lib, "urlmon.lib")
#pragma comment(lib, "wininet.lib")
void data();
void test(std::string received) {
data();
Sleep(1);
}
void data() {
- >>HINTERNET connect = InternetOpen(L"MyBrowser", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
HINTERNET OpenAddress = InternetOpenUrl(connect, L"web page", NULL, 0, INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_KEEP_CONNECTION, 0);
char dataReceived[5000];
std::string received;
DWORD NumberOfBytesRead = 0;
while (InternetReadFile(OpenAddress, dataReceived, 5000, &NumberOfBytesRead) && NumberOfBytesRead)
{
received += std::string(dataReceived);
}
- >>InternetCloseHandle(connect);
InternetCloseHandle(OpenAddress);
test(received);
}
int main() {
data();
}
Please tell me how to normally move the selected lines (- >>) outside the function to run them once?
Change data() and test() to take an HINTERNET as a parameter, and then main() can create the HINTERNET to pass in, eg:
#include <iostream>
#include <urlmon.h>
#include <wininet.h>
#pragma comment(lib, "urlmon.lib")
#pragma comment(lib, "wininet.lib")
void data(HINTERNET connect);
void test(HINTERNET connect, std::string received) {
data(connect);
Sleep(1);
}
void data(HINTERNET connect) {
HINTERNET OpenAddress = InternetOpenUrl(connect, L"web page", NULL, 0, INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_KEEP_CONNECTION, 0);
char dataReceived[5000];
std::string received;
DWORD NumberOfBytesRead = 0;
while (InternetReadFile(OpenAddress, dataReceived, 5000, &NumberOfBytesRead) && NumberOfBytesRead)
{
received += std::string(dataReceived);
}
InternetCloseHandle(OpenAddress);
test(connect, received);
}
int main() {
HINTERNET connect = InternetOpen(L"MyBrowser", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
data(connect);
InternetCloseHandle(connect);
}

Send POST data via HttpOpenRequestA

I'm trying to send my PC Name to my local server and save it in a file.
There is my code:
#include <stdio.h>
#include <windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <cstring>
#include <Lmcons.h>
#include <unistd.h>
#include <stdlib.h>
#include <WinInet.h>
#include <bits/stdc++.h>
#pragma comment( lib,"Wininet.lib")
using namespace std;
int main() {
TCHAR name [ UNLEN + 1 ];
DWORD size = UNLEN + 1;
static CHAR hdrs[] = "Content-Type: application/x-www-form-urlencoded";
if (GetUserName( (TCHAR*)name, &size ));
static CHAR frmdata[] = "data=", name;
HINTERNET hSession = InternetOpenA("http generic", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
HINTERNET hConnect = InternetConnect(hSession, "127.0.0.1", INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
HINTERNET hRequest = HttpOpenRequestA(hConnect, "POST", "/test/index.php", NULL, NULL, NULL, 0, 1);
HttpSendRequestA(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));
}
I've tried use static CHAR frmdata[] = "data=" + name; also but not works.
This is the error that I receive:
error: invalid operands of types 'const char [6]' and 'TCHAR [257] {aka char [257]}' to binary 'operator+'|
You can't concatenate char[] arrays like you are trying to do. Allocate a separate buffer of sufficient size and copy the input strings into it, eg:
#include <windows.h>
#include <Lmcons.h>
#include <WinInet.h>
#include <cstring>
//#include <cstdio>
using namespace std;
#pragma comment( lib, "Wininet.lib")
int main()
{
static char hdrs[] = "Content-Type: application/x-www-form-urlencoded";
char name[UNLEN + 1] = {};
DWORD size = UNLEN + 1;
GetUserNameA(name, &size);
char frmdata[5 + UNLEN + 1] = {};
strcpy(frmdata, "data=");
strcat(frmdata, name);
// alternatively:
// sprintf(frmdata, "data=%s", name);
HINTERNET hSession = InternetOpenA("http generic", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (!hSession) {
// error handling...
}
HINTERNET hConnect = InternetConnectA(hSession, "127.0.0.1", INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
if (!hConnect) {
// error handling...
}
HINTERNET hRequest = HttpOpenRequestA(hConnect, "POST", "/test/index.php", NULL, NULL, NULL, 0, 1);
if (!hRequest) {
// error handling...
}
if (!HttpSendRequestA(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata))) {
// error handling...
}
InternetCloseHandle(hRequest);
InternetCloseHandle(hConnect);
InternetCloseHandle(hSession);
return 0;
}
Alternatively, you can use a single buffer, just make it larger, and have GetUserNameA() populate a portion of it, then you don't need to make a copy afterwards, eg:
int main()
{
...
char frmdata[5 + UNLEN + 1] = "data=";
DWORD size = UNLEN + 1;
GetUserNameA(&frmdata[5], &size);
...
}
You need to concatenate, which std::string can do for you. You should also use the same base character type to avoid the need for additional conversions.
char name [ UNLEN + 1 ];
DWORD size = UNLEN + 1;
GetUserNameA( name, &size );
std::string frmdata;
frmdata += "data=";
frmdata += name;
...
HttpSendRequestA(hRequest, hdrs, strlen(hdrs), frmdata.data(), (DWORD)frmdata.size());
In case you want to transport unicode data (use std::wstring in that case) you will need to convert your data string to proper utf-8 (lookup WideCharToMultiByte).

Get information about device using SetupAPI

I have a printer connected with USB port and I want to get some information about it. I am using SetupDiEnumDeviceInfo function from setupapi to get information. I am doing everything as it is described in MSDN.
#include <string>
#include <windows.h>
#include <vector>
#include <iostream>
#include <setupapi.h>
#include <winerror.h>
#pragma comment (lib, "SetupAPI.lib")
static GUID GUID_DEVCLASS_PORTS = { 0x4d36e978, 0xe325, 0x11ce, 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18 };
int main()
{
SP_DEVINFO_DATA devInfoData;
HDEVINFO deviceInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_PORTS, 0, 0, DIGCF_PRESENT);
devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
DWORD nDevice = 0;
if (SetupDiEnumDeviceInfo(deviceInfo, nDevice, &devInfoData))
{
}
return 0;
}
The problem is that I am always getting false result.
GetLastError() function retruns 259.
What am I doing wrong?
this is my sample. I add the devguid.h, and use GUID_DEVCLASS_USB.
#include <string>
#include <windows.h>
#include <setupapi.h>
#include <devguid.h>
#pragma comment (lib, "SetupAPI.lib")
int main()
{
int res = 0;
HDEVINFO hDevInfo;
SP_DEVINFO_DATA DeviceInfoData = { sizeof(DeviceInfoData) };
// get device class information handle
hDevInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_USB, 0, 0, DIGCF_PRESENT);
if (hDevInfo == INVALID_HANDLE_VALUE)
{
res = GetLastError();
return res;
}
// enumerute device information
DWORD required_size = 0;
for (int i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData); i++)
{
DWORD DataT;
char friendly_name[2046] = { 0 };
DWORD buffersize = 2046;
DWORD req_bufsize = 0;
// get device description information
if (!SetupDiGetDeviceRegistryPropertyA(hDevInfo, &DeviceInfoData, SPDRP_CLASSGUID, &DataT, (PBYTE)friendly_name, buffersize, &req_bufsize))
{
res = GetLastError();
continue;
}
char temp[512] = { 0 };
sprintf_s(temp, 512, "USB device %d: %s", i, friendly_name);
puts(temp);
}
return 0;
}

Encountering seg fault in wininet ftp program

So i found this c++ program and i thought i would use it to automate backing up my files to my desktop ftp server but it always runs into the same seg fault problem, After checking the ftp server logs i can see that is does actually connect to the ftp server and log in with the user name and password but it when it reaches the actual upload part it crashes.
I ran it through the debugger in dev c++ and it says "Access violation (Seg faut)"
Is this a bug in wininet? and if so is there some sort of workaround?
#include <windows.h>
#include <wininet.h>
#pragma comment(lib, "wininet")
#include <fstream>
#include <string.h>
int send(const char * ftp, const char * user, const char * pass, const char * pathondisk, char * nameonftp)
{
HINTERNET hInternet;
HINTERNET hFtpSession;
hInternet = InternetOpen(NULL,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
if(hInternet==NULL)
{
cout << GetLastError();
//system("PAUSE");
return 1;
}
hFtpSession = InternetConnect(hInternet,
(LPTSTR)ftp, INTERNET_DEFAULT_FTP_PORT,
(LPTSTR)user, (LPTSTR)pass, INTERNET_SERVICE_FTP,
INTERNET_FLAG_PASSIVE, 0);
if(hFtpSession==NULL)
{
cout << GetLastError();
//system("PAUSE");
return 1;
}
Sleep(1000);
char * buf=nameonftp;
strcat(buf,".txt");
if (!FtpPutFile(hFtpSession, (LPTSTR)pathondisk, (LPTSTR)buf, FTP_TRANSFER_TYPE_ASCII, 0)) {
cout << GetLastError();//this is never reached
return 1;
}
Sleep(1000);
InternetCloseHandle(hFtpSession);
InternetCloseHandle(hInternet);
return 0;
}
int main() {
send("127.0.0.1","testuser","test","file.pdf","backup");
return 0;
}
You must not modify string literals. Copy the string to a new buffer to edit the contents.
Also, you should use hogeA() APIs to have the system use ANSI charset explicitly.
Try this:
#include <windows.h>
#include <wininet.h>
#pragma comment(lib, "wininet")
#include <iostream>
#include <fstream>
#include <string.h>
using std::cout;
int send(const char * ftp, const char * user, const char * pass, const char * pathondisk, const char * nameonftp)
{
HINTERNET hInternet;
HINTERNET hFtpSession;
hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if(hInternet==NULL)
{
cout << GetLastError();
//system("PAUSE");
return 1;
}
hFtpSession = InternetConnectA(hInternet,
ftp, INTERNET_DEFAULT_FTP_PORT,
user, pass, INTERNET_SERVICE_FTP,
INTERNET_FLAG_PASSIVE, 0);
if(hFtpSession==NULL)
{
cout << GetLastError();
//system("PAUSE");
return 1;
}
Sleep(1000);
char * buf=new char[strlen(nameonftp) + 4 + 1];
strcpy(buf, nameonftp);
strcat(buf, ".txt");
if (!FtpPutFileA(hFtpSession, pathondisk, buf, FTP_TRANSFER_TYPE_ASCII, 0)) {
cout << GetLastError();
delete[] buf;
return 1;
}
delete[] buf;
Sleep(1000);
InternetCloseHandle(hFtpSession);
InternetCloseHandle(hInternet);
return 0;
}
int main() {
send("127.0.0.1", "testuser", "test", "file.pdf", "backup");
return 0;
}

C++ FTP writing to file is not working

I wrote this code that is SUPPOSED to write to a file on an ftp server, but it doesn't work. The file stays 0 bytes. There are also no errors. Here's my code:
#include <windows.h>
#include <wininet.h>
#include <stdio.h>
int main()
{
int error=0;
char buffer[256];
char *text="Hello world.";
HINTERNET hOpen=InternetOpen("",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,INTERNET_FLAG_PASSIVE);
InternetGetLastResponseInfo((LPDWORD)error,(LPSTR)buffer,(LPDWORD)256);
printf("hOpen:%d:%s\n",error,buffer);
HINTERNET hConnect=InternetConnect(hOpen,"diabloip.host22.com",INTERNET_DEFAULT_FTP_PORT,"MY_USER_NAME","MY_PASSWORD",INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,0);
InternetGetLastResponseInfo((LPDWORD)error,(LPSTR)buffer,(LPDWORD)256);
printf("hConnect:%d:%s\n",error,buffer);
HINTERNET hFile=FtpOpenFile(hConnect,"diabloip.host22.com/public_html/log.txt",GENERIC_WRITE,FTP_TRANSFER_TYPE_ASCII,0);
InternetGetLastResponseInfo((LPDWORD)error,(LPSTR)buffer,(LPDWORD)256);
printf("hFile:%d:%s\n",error,buffer);
InternetWriteFile(hFile,text,strlen(text),NULL);
return 0;
}
The problem is passing NULL as the last parameter to InternetWriteFile. It is not an optional parameter and if you had error checking for that call as the rest you'd see GetLastError returns 87, or ERROR_INVALID_PARAMETER.
This works correctly and cleans up some of the other issues with incorrect parameters and the excessive casting that masks the issues.
#include <windows.h>
#include <wininet.h>
#include <stdio.h>
#pragma comment(lib, "wininet.lib")
void PrintStatus(const char* title)
{
DWORD error = 0;
DWORD sz = 256;
char buffer[256];
InternetGetLastResponseInfo(&error, buffer, &sz);
printf("%s:%u:%s\n", title, error, buffer);
}
int main()
{
const char *text = "Hello world.";
HINTERNET hOpen = InternetOpen("", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_FLAG_PASSIVE);
PrintStatus("hOpen");
HINTERNET hConnect = InternetConnect(hOpen, "localhost", INTERNET_DEFAULT_FTP_PORT, "test", "test", INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
PrintStatus("hConnect");
HINTERNET hFile = FtpOpenFile(hConnect, "log.txt", GENERIC_WRITE, FTP_TRANSFER_TYPE_ASCII, 0);
PrintStatus("hFile");
DWORD wb = 0;
BOOL Success = InternetWriteFile(hFile, text, strlen(text), &wb);
if(!Success)
{
DWORD err = GetLastError();
printf("InternetWriteFile - Error = %u\n", err);
}
PrintStatus("InternetWriteFile");
InternetCloseHandle(hOpen);
return 0;
}