I have this program:
#include <string>
#include <iostream>
#include <fstream>
#include <windows.h>
#include <wininet.h>
#include <winsock.h>
#include <stdio.h>
#include <stdarg.h>
using namespace std;
int main()
{
HINTERNET hOpen, hURL;
LPCTSTR NameProgram = "UA"; // LPCWSTR == Long Pointer to Const Wide String
LPCTSTR Website;
char file[101];
unsigned long read;
//Always need to establish the internet connection with this funcion.
if ( !(hOpen = InternetOpen(NameProgram, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0 )))
{
cerr << "Error in opening internet" << endl;
return 0;
}
Website = "www.c-jump.com";
hURL = InternetOpenUrl( hOpen, Website, NULL, 0, 0, 0 ); //Need to open the URL
InternetReadFile(hURL, file, 100, &read);
while (read == 100)
{
InternetReadFile(hURL, file, 100, &read);
file[read] = '\0';
cout << file;
}
cout << endl;
InternetCloseHandle(hURL);
return 0;
}
which I've compiled like this:
C:\Users\user\Desktop>cl.exe new.cpp /link "wininet.lib"
Microsoft (R) C/C++ Optimizing Compiler Version 19.10.25019 for x86
Copyright (C) Microsoft Corporation. All rights reserved.
new.cpp
C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.10.25017\include\xlocale(314): warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc
C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.10.25017\include\exception(366): warning C4577: 'noexcept' used with no exception handling mode specified; termination on exception is not guaranteed. Specify /EHsc
Microsoft (R) Incremental Linker Version 14.10.25019.0
Copyright (C) Microsoft Corporation. All rights reserved.
/out:new.exe
wininet.lib
new.obj
I run the exe and get no output, I'm expecting the HTML response from the URL to be printed to stdout. I run the code in a debugger and get the following error returned when the InternetOpenUrlA function returns:
ERROR_SXS_ACTIVATION_CONTEXT_DISABLED (00002EE6)
I'm running Windows on Windows 10.
Could anyone shed any light on what this means and how one could resolve the issue? I had the same code working earlier yesterday and then suddenly it stopped working, with some Windows updates getting installed in between.
Many many thanks
Charlie
The error is probably ERROR_INTERNET_UNRECOGNIZED_SCHEME because your URL does not have a scheme/protocol. Just fix the URL: Website = "http://www.c-jump.com"; Your read loop also has issues, you throw away the first 100 bytes! There is also no guarantee that it can read 100 bytes each time.
You can also attempt to fix the URL:
DWORD DumpResponse(const char *URL)
{
LPCSTR agent = "Stackoverflow Example";
DWORD error, read;
HINTERNET hInet, hConn;
char data[101], urlbuf[INTERNET_MAX_URL_LENGTH];
const char *defscheme = "http";
URL_COMPONENTSA uc;
ZeroMemory(&uc, sizeof(uc));
uc.dwStructSize = sizeof(uc);
BOOL crack = InternetCrackUrlA(URL, 0, 0, &uc);
error = GetLastError();
printf("DBG: InternetCrackUrlA error %d\n", crack ? 0 : error);
if (!crack && error == ERROR_INTERNET_UNRECOGNIZED_SCHEME && strlen(defscheme) + 3 + strlen(URL) < INTERNET_MAX_URL_LENGTH)
{
// Prepend a protocol
sprintf(urlbuf, "%s://%s", defscheme, URL);
URL = urlbuf;
}
else if (!crack)
{
return error;
}
hInet = InternetOpenA(agent, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (!hInet) return GetLastError();
hConn = InternetOpenUrlA(hInet, URL, NULL, 0, 0, 0);
error = GetLastError();
if (!hConn)
{
InternetCloseHandle(hInet);
printf("DBG: InternetOpenUrl failed with error %d\n", error);
return error;
}
error = 0;
for (;;)
{
if (!InternetReadFile(hConn, data, sizeof(data) - 1, &read))
{
error = GetLastError();
break;
}
if (0 == read) break; // Done
data[read] = '\0';
printf("%s", data);
}
InternetCloseHandle(hInet);
InternetCloseHandle(hConn);
return error;
}
int main()
{
printf("----\nDumpResponse returned %d\n", DumpResponse("www.c-jump.com"));
}
Related
I am trying to get my harddisk serial ID by using StorPortGetDeviceInformation, but it gives me an error: identifier StorPortGetDeviceInformation is undefined. I am also seeing an error such as "Error (active) E0020 identifier "PRTL_RUN_ONCE_INIT_FN" is undefined mutante C:\Program Files (x86)\Windows Kits\10\Include\10.0.22621.0\km\ntddk.h 2225 "
I would be happy if someone could take a look at see why this does not work. Below is the code I am using (from an empty Driver Project created in Visual Studio 2022):
#include <Windows.h>
#include <storport.h>
#include <stdio.h>
#include <ntddk.h>
int main()
{
// Enumerate the physical drives on the system
for (int i = 0; i < 256; i++)
{
// Open a handle to the storage device
WCHAR deviceName[32];
swprintf_s(deviceName, L"\\\\.\\PhysicalDrive%d", i);
HANDLE hDevice = CreateFile(deviceName,
GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
continue;
}
// Allocate a buffer to hold the serial ID
ULONG serialIdSize = sizeof(STORAGE_DEVICE_ID_DESCRIPTOR);
PSTORAGE_DEVICE_ID_DESCRIPTOR pSerialId =
(PSTORAGE_DEVICE_ID_DESCRIPTOR)malloc(serialIdSize);
if (pSerialId == NULL)
{
printf("Failed to allocate buffer.\n");
CloseHandle(hDevice);
return 1;
}
// Retrieve the serial ID
ULONG bytesReturned;
if (!StorPortGetDeviceInformation(hDevice,
StorageDeviceIdDescriptor, pSerialId, serialIdSize, &bytesReturned))
{
printf("Failed to get device information.\n");
free(pSerialId);
CloseHandle(hDevice);
return 1;
}
// Print the serial ID
printf("Serial ID of disk %d: %S\n", i, pSerialId->Identifiers[0].Identifier);
// Clean up
free(pSerialId);
CloseHandle(hDevice);
}
return 0;
}
What I done so far:
Created an empty driver project
Installed WDK and can be found in C:\Program Files (x86)\Windows Kits\10
Tried to link against the storport.lib library at C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22621.0\km\x64\storport.lib
What I expected:
I can call StorPortGetDeviceInformation from my driver.
(https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersaddresses)
Why are some of the user friendly names in PIP_ADAPTER_ADDRESSES unprintable? (aswell as a few other attributes such as dns suffix)
By unprintable, I mean containing non-printable characters. for exmaple, the first character in one of the friendly names I tested had a unicode value fo 8207 (decimal)
A minimal complete viable example
#include <winsock2.h>
#include <iphlpapi.h>
#include <vector>
#include <iostream>
int main()
{
PIP_ADAPTER_ADDRESSES adapterAddresses;
DWORD dwReqSize;
DWORD retVal;
DWORD count = 0;
std::string tempForWstringConv;
retVal = GetAdaptersAddresses(AF_INET, GAA_FLAG_INCLUDE_PREFIX, NULL, NULL, &dwReqSize); // for knowing the required size
if (retVal != ERROR_BUFFER_OVERFLOW) {
return -1;
}
adapterAddresses = (PIP_ADAPTER_ADDRESSES)malloc(dwReqSize);
retVal = GetAdaptersAddresses(AF_INET, GAA_FLAG_INCLUDE_PREFIX, NULL, adapterAddresses, &dwReqSize); // this time actually getting the desired content
if (retVal != ERROR_SUCCESS) {
return -1;
}
for (PIP_ADAPTER_ADDRESSES adapter = adapterAddresses; adapter != NULL; adapter = adapter->Next)
{
//outLog.push_back(Adapter());
printf("\tFriendly name: %ls\n", adapter->FriendlyName);
}
return 0;
}
I finally found A solution!
meet _setmode(_fileno(stdout), _O_U16TEXT);
the problem was that the output buffer wasn't allowing these characters because the mode was incorrect. Alas, our desired output:
inorder to use this you MUST A: switch all occurences of cout to wcou; B: switch all occurences of printf to wprintf. C: include and
I trying to write a very simple app to debug a Win32 64-bit app. My end goal is to get the TIB and PEB of the remote thread, but for some reason the way I did this on 32-bit app is not working for 64-bit ones (Aside from looking at Esp vs Rsp and checking SegFs vs SegGs). The code I'm trying to use is here:
#include <windows.h>
#include <stdio.h>
#include <tlhelp32.h>
int main(int argc, char *argv[]){
LDT_ENTRY entry;
DWORD pid;
HANDLE hThread;
HANDLE hSnapshot;
CONTEXT context;
context.ContextFlags = CONTEXT_CONTROL;
if(argc < 2){
printf("Usage: %s PID\n", argv[0]);
exit(1);
}
pid = atoi(argv[1]);
THREADENTRY32 te32;
te32.dwSize = sizeof(te32);
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD,0);
while(Thread32Next(hSnapshot, &te32)){
if(pid == te32.th32OwnerProcessID){
hThread = OpenThread(THREAD_ALL_ACCESS, 0, te32.th32ThreadID);
if(!hThread)
exit(1);
if(SuspendThread(hThread) == (DWORD) -1)
exit(1);
if(!GetThreadContext(hThread, &context))
exit(1);
printf("Rsp = 0x%x\n", context.Rsp);
if(!GetThreadSelectorEntry(hThread, context.SegGs, &entry)){
LPSTR buff = NULL;
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buff, 0, NULL);
printf("Error: %s\n", buff); //ERROR_NOT_SUPPORTED 50 0x32 The request is not supported.
LocalFree(buff);
exit(1);
}
}
}
CloseHandle(hSnapshot);
return 0;
}
but it's always throwing an error at "GetThreadSelectorEntry". The error code that's thrown is ERROR_NOT_SUPPORTED: The request is not supported.
I am not able to understand why it's not supported. Does anyone know why?
[EDIT]
Okay GetThreadSelectorEntry is not available to x86_64 processes, does anyone know how I can get the TIB/PEB addresses of a remote process?
I'm aware that the GetTcpTable2 api is supported only on windows vista and above versions, hence the code checks for the OS version and only then enters the loop that calls the api. I'm compiling the code on windows 7, visual studio 2008 and the executable runs fine on windows 7 and other OS except Windows XP, the error thrown is :
The code snippet is:`
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
// Need to link with Iphlpapi.lib and Ws2_32.lib
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
/* Note: could also use malloc() and free() */
int main()
{
OSVERSIONINFOEX osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
GetVersionEx((OSVERSIONINFO *)&osvi);
if(osvi.dwMajorVersion>=6)
{
// Declare and initialize variables
PMIB_TCPTABLE2 pTcpTable;
ULONG ulSize = 0;
DWORD dwRetVal = 0;
char szLocalAddr[128];
char szRemoteAddr[128];
struct in_addr IpAddr;
int i;
pTcpTable = (MIB_TCPTABLE2 *) MALLOC(sizeof (MIB_TCPTABLE2));
if (pTcpTable == NULL)
{
printf("Error allocating memory\n");
return 1;
}
ulSize = sizeof (MIB_TCPTABLE);
// Make an initial call to GetTcpTable2 to
// get the necessary size into the ulSize variable
if ((dwRetVal = GetTcpTable2(pTcpTable, &ulSize, TRUE)) ==
ERROR_INSUFFICIENT_BUFFER)
{
FREE(pTcpTable);
pTcpTable = (MIB_TCPTABLE2 *) MALLOC(ulSize);
if (pTcpTable == NULL)
{
printf("Error allocating memory\n");
return 1;
}
}
}
else
{
printf("Unsupported OS");
}
return 0;
}
`How do I get the executable to work on Windows XP without crashing/throwing the error shown in attached image?
Actually the coding below is what I tried to execute. When I tried to execute this using Microsoft Visual Studio 2012, there is an error.
Error error LNK2019: unresolved external symbol _cvPyrSegmentation referenced in function "void __cdecl START_SEGMENT(int)" (?START_SEGMENT##YAXH#Z)
Error error LNK1120: 1 unresolved externals
But I asked my friend to execute this code using his laptop, it works just fine.No error. But he is using Microsoft Visual Studio 2010 instead of me using Visual Studio 2012..I wonder why there is an error when I execute this code but when my friend execute it, no error.
So I removed some header and the coding looks like the one that I ask from the beginning( from this Question.The one with ""Error error C3861: 'cvPyrSegmentation': identifier not found ""..
After I removed some header, there is no more Error LNK1120. But there is ""Error error C3861: 'cvPyrSegmentation': identifier not found""...
Blank ...Too many error for a newbie.Learning process never be easy .yeahhh!
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc_c.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/legacy/legacy.hpp>
#include <stdio.h>
static void help(void)
{
printf("\nThis program present the function of pyramid segmentation which is
cvcvPyrSegmentation()\n""we can controlled the value of threshold by creating
the taskbar\n""Usage :\n");
}
IplImage* image[2] = { 0, 0 }, *image0 = 0, *image1 = 0;
CvSize size;
int w0, h0,i;
int threshold1, threshold2;
int l,level = 4;
int sthreshold1, sthreshold2;
int l_comp;
int block_size = 1000;
float parameter;
double threshold;
double rezult, min_rezult;
int filter = CV_GAUSSIAN_5x5;
CvConnectedComp *cur_comp, min_comp;
CvSeq *comp;
CvMemStorage *storage;
CvPoint pt1, pt2;
static void START_SEGMENT(int a)
{
(void) a;
cvPyrSegmentation(image0, image1, storage, &comp, level, threshold1+1,
threshold2+1);
cvShowImage("Segmentation", image1);
}
int main( int argc, char** argv )
{
char* filename;
help();
filename = argc == 2 ? argv[1] : (char*)"C:/Users/acer/Documents/Visual Studio
2012/Projects/me2.jpg";
if( (image[0] = cvLoadImage( filename, 1)) == 0 )
{
help();
printf("Cannot load fileimage - %s\n", filename);
return -1;
}
cvNamedWindow("Source", 0);
cvShowImage("Source", image[0]);
cvNamedWindow("Segmentation", 0);
storage = cvCreateMemStorage ( block_size );
image[0]->width &= -(1<<level);
image[0]->height &= -(1<<level);
image0 = cvCloneImage( image[0] );
image1 = cvCloneImage( image[0] );
// segmentation of the color image
l = 1;
threshold1 =255;
threshold2 =30;
START_SEGMENT(1);
sthreshold1 = cvCreateTrackbar("Threshold1", "Segmentation", &threshold1, 255,
START_SEGMENT);
sthreshold2 = cvCreateTrackbar("Threshold2", "Segmentation", &threshold2, 255,
START_SEGMENT);
cvShowImage("Segmentation", image1);
cvWaitKey(0);
cvDestroyWindow("Segmentation");
cvDestroyWindow("Source");
cvReleaseMemStorage(&storage );
cvReleaseImage(&image[0]);
cvReleaseImage(&image0);
cvReleaseImage(&image1);
return 0;
}
#ifdef _EiC
main(1,"pyramid_segmentation.c");
#endif
Having fixed your compilation problem, you now have a linker problem.
You need to follow the instructions in the OpenCV documentation to find out how to link their libraries to your binary.
You'll start with -lcv and potentially have to add some additional libraries.