winapi,language-agnostic,winsock,endianness , gethostbyname and endianness - how are the bytes returned?

gethostbyname and endianness - how are the bytes returned?


Tag: winapi,language-agnostic,winsock,endianness

On my (Intel) x86 machine, I've noticed that if I printf the results of gethostbyname for localhost, I get 100007F, even though the MSDN documentation states it should return the IP in network byte order, aka big endian. I searched a bit and found this topic. Based on the answers there, I've deduced the sequence of bytes will be the same no matter the endianness, so, for localhost, I'd have this in memory on both Intel and AMD chips:


Thus, reading that memory with an Intel chip results in a 'reversed' result, while on an AMD CPU, I'd get 0x7F000001. Is that assumption correct? It seems like the only possible explanation, but I want to make sure.

This is the code I'm using:


#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

// Need to link with Ws2_32.lib
#pragma comment(lib, "ws2_32.lib")

int main(int argc, char **argv)

    // Declare and initialize variables
    WSADATA wsaData;
    int iResult;

    DWORD dwError;
    int i = 0;

    struct hostent *remoteHost;
    char *host_name;
    struct in_addr addr;

    char **pAlias;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;

    host_name = "localhost";

    // If the user input is an alpha name for the host, use gethostbyname()
    // If not, get host by addr (assume IPv4)
    if (isalpha(host_name[0])) {        /* host address is a name */
        printf("Calling gethostbyname with %s\n", host_name);
        remoteHost = gethostbyname(host_name);
    else {
        printf("Calling gethostbyaddr with %s\n", host_name);
        addr.s_addr = inet_addr(host_name);
        if (addr.s_addr == INADDR_NONE) {
            printf("The IPv4 address entered must be a legal address\n");
            return 1;
            remoteHost = gethostbyaddr((char *)&addr, 4, AF_INET);

    if (remoteHost == NULL) {
        dwError = WSAGetLastError();
        if (dwError != 0) {
            if (dwError == WSAHOST_NOT_FOUND) {
                printf("Host not found\n");
                return 1;
            else if (dwError == WSANO_DATA) {
                printf("No data record found\n");
                return 1;
            else {
                printf("Function failed with error: %ld\n", dwError);
                return 1;
    else {
        printf("Function returned:\n");
        printf("\tOfficial name: %s\n", remoteHost->h_name);
        for (pAlias = remoteHost->h_aliases; *pAlias != 0; pAlias++) {
            printf("\tAlternate name #%d: %s\n", ++i, *pAlias);
        printf("\tAddress type: ");
        switch (remoteHost->h_addrtype) {
        case AF_INET:
        case AF_INET6:
        case AF_NETBIOS:
            printf(" %d\n", remoteHost->h_addrtype);
        printf("\tAddress length: %d\n", remoteHost->h_length);

        if (remoteHost->h_addrtype == AF_INET) {
            while (remoteHost->h_addr_list[i] != 0) {
                addr.s_addr = *(u_long *)remoteHost->h_addr_list[i++];
                printf("\tIPv4 Address #%d: %X %s\n", i, addr.s_addr, inet_ntoa(addr));
        else if (remoteHost->h_addrtype == AF_INET6)
            printf("\tRemotehost is an IPv6 address\n");
    return 0;

The output:

enter image description here

NOTE: I've had a friend run this on his AMD CPU, and surprisingly, apparently it's 100007F for him as well. Is my previous assumption wrong, or is my friend drunk?


The addresses contained in the hostent structure are in network byte order.

If you have code that suggests otherwise then you are misinterpreting that code and reaching the wrong conclusion.

In network byte order, on a little endian host, is 0x0100007f. To see how this works, remember that on a little endian host, the least significant byte is stored first. That's 0x7f. So the bytes appear in this order in memory, 0x7f, 0x00, 0x00, 0x01. And that therefore represents

Now, those same bytes on a big endian host would represent a different 32 bit value. On a big endian host, the first byte if the most significant, and so 0x7f, 0x00, 0x00, 0x01 would represent the value 0x7f000001.


New window opening with parent window's controls

Sorry for english slaughter but i can't find anything about that. I'm trying to open an empty window in c++ with winapi but new window opening with parent window's controls like a clone. case VBTN: { vsa1 = CreateWindowEx(NULL, L"Window Class", L"Test", WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, CW_USEDEFAULT, CW_USEDEFAULT, 350,...

winapi: from HDC to an HBITMAP

I would like to do something which I believe is fairly simple but since I am new to the winapi I am finding a lot of problems. Basically I have an HDC (which I am BitBlitting from a loaded Bitmap) and I am drawing a rectangle on it. Then I...

MASM console window creation troubles (maybe my stack frame??)

I'm having trouble with the following code snippet. I'm compiling an asm file with a c++ file using visual studio express 2012. I've tried debugging calculating the addresses of the stack pointers and memory locations (still learning assembly obviously), but can't find a fault. (As I'm new it's probably something...

Can a dialog intercept drag'n'drop messages passed to its controls?

If a dialog registers some of its controls as drop-targets, will drag'n'drop messages intended for those controls pass through the dialog's message processing in a way that the dialog can register a message handler to be notified/intercept those messages? In a similar fashion to this question, I want to catch...

std::vector content change when read inside the main()

I was writing this function to search a file inside the computer but i encountered a problem: When I read the files that have been found during the search(using the for cycle inside the main() ) the directory are broken. With some debugging I saw that when pushed inside the...

Is a StatusBar created in simple mode by default?

When a StatusBar is first created, for example: HWND hStatusBar = CreateWindowEx(0, STATUSCLASSNAME, "", WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, hWnd, 0, GetModuleHandle(NULL), NULL); Is it created in simple mode or in multiple-part mode? or maybe this is not guaranteed and it is better to set the mode I...

GetWindowsDirectory() API returns wrong (vba\vb6)

on my Windows-Terminal user, I'm trying to have two application point to the same Windows directory, one written in VBA one in VB6. When calling the GetWindowsDirectory() API from VB6 it returns the correct path C:\documents and settings\%user%\Windows When calling it from VBA macro, it returns C:\Windows Notice that same...

Hide Window from taskbar without using WS_EX_TOOLWINDOW

I have a main Window and an About Window, The About Window is opened from the main Window, but the problem is that the About Window is shown in the taskbar! I have found that in order to hide a Window from the taskbar, I can use the WS_EX_TOOLWINDOW style,...

ICallFactory with 32-bit and 64-bit type libraries side by side

I have a in-proc COM server for which I want to build 32-bit and 64-bit versions. I can do this with no problem. However, I am encountering some issues when both versions are registered. I am not using ATL. In my DllRegisterServer function, I am using RegisterTypeLibForUser. I am acquiring...

How can I send data between 2 applications using SendMessage?

I have 2 applications- Manager with this code: procedure TForm1.CopyData(var Msg: TWMCopyData); var sMsg: String; begin if IsIconic(Application.Handle) then Application.Restore; sMsg := PWideChar(Msg.CopyDataStruct.lpData); Caption := Caption+'#'+sMsg; Msg.Result := 123; end; procedure TForm1.Button1Click(Sender: TObject); const WM_MY_MESSAGE = WM_USER + 1; var h: HWND; begin Caption := 'X'; h := FindWindow('TForm1', 'Client');...

Obtain thread handles/id of a specific process

I have a multi-threaded embedded architecture that contains 6 application specific processes which are executed when the initialization process is executed. Likewise, each have their own number of threads that are running. What i want to do is suspend the running threads of 1 particular process based on whether the...

How can a dialog become responsive while waiting for a call to DoModal() to return?

A button on a dialog causes a child dialog to be created, and displayed modally. e.g: void ParentDialog::OnButton() { ChildDialog dlg; int ret = dlg.DoModal(); } The parent dialog is initially unresponsive as expected. But, the child dialog also makes COM calls to a server module, which causes the server...

Does LoadLibrary return NULL or an error code < 32 on failure?

The MSDN documentation states If the function succeeds, the return value is a handle to the module. If the function fails, the return value is NULL. To get extended error information, call GetLastError. while Microsoft support has a list of return values less than 32 that indicate an error The...

Count digits in file using WinApi functions

I need to count digits in file using CreateFile and ReadFile methods from <Windows.h>. Here's what I have: int CountDigitsInFile(PCTSTR path) { HANDLE hFile = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { _tprintf_s(TEXT("Open File Error")); return NULL; } TCHAR data[100]; DWORD dwRead; DWORD dwFileSize =...

MessageBox won't work when handling WM_DESTROY event from DialogBox

While elaborating an answer for another question (by myself), I've come up with the idea of using a MessageBox to report the result of my dialog box. It is a WinAPI modal dialog box created with the DialogBox() function. However, I noticed that handling WM_DESTROY in the dialog's procedure function...

Generating a self-signed X509Certificate2 certificate with its private key

I'm not the most familiar with the unmanaged cryptography library in the Windows API, but alas I am trying to generate a self-signed X509Certificate2 certificate. Here is the complete code: using System; using System.Security; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Security.Cryptography.X509Certificates; namespace Example { [StructLayout(LayoutKind.Sequential)] public struct SystemTime { public short...

Read lines from file async using WINAPI ReadFile

I need to read several lines from file simultaneously, i.e. asynchronously. Lines in file are of the same size. For instance, I need to read the second and the fourth lines of file to separate variables or to an array. I'm more used to c#'s async/await and all these OVERLAPPED...

Why/how does winapi reverse the order of messages?

Consider the following code: CCritialSection listLock; std::list<CString> messageList; extern MyApp theApp; // public inheritance from CWinApp const int aMessageNumber = WM_APP + 123; void MyApp::EnqueueMessageForUIThread( const CString message ) { CSingleLock lock( &listLock, TRUE ); messageList.push_back( message ); theApp.m_pMainWnd->PostMessage( aMessageNumber ); } void MyApp:PopupMessageFromNonUIThread( void) { // This function is...

Accessing GetConsoleHistoryInfo() from managed code

I've got a vaguely Java background and just installed Visual Studio Community 2015. Playing about with it so have a console app up and running and wanted to use above function after attaching to a different Console. Trouble is I have no idea about the appropriate declaration for this function...

Populating a List Control with the sorted contents of an `std::multimap`?

As a follow-up to this question, I need a way to access my data by index. But the data needs to be sorted by timestamp, contain a filepath as a value, and be displayed in real-time as new elements are discovered. Considering that multiple files/folders could potentially contain an identical...

Passing HWND through to a method and storing in a class

I am calling the following: // hMainWindow is a correctly functioning window handle app.GetMainWindowInfo().SetHndToWindow( hMainWindow ); Here are my classes: class App : public BaseClass { public: WindowInfo& GetMainWindowInfo(); void SetMainWindowInfo( unique_ptr<WindowInfo> windowInfo ); private: WindowInfo mainWindowInfo; }; class WindowInfo { public: HWND& GetHndToWindow() const; //void SetHndToWindow( HWND hndToWindow );...

Get list of process

I need to get the list of process with their PID. I know how to get the PID by its handle and viceversa, but the problem is that I'm not the one who create the process, so I don't have the handle nor the PID. I didn't find exactly information...

If statement not working in vb6

I want to make a program which could close a window with the title "Personalization" in vb6. The problem is that the if statement is not working.Here's my code(it only finds a window named "Personalization" without closing it): Option Explicit Private Sub Command1_Click() Timer1.Enabled = Not Timer1.Enabled End Sub Private...

Is it valid to mutilayered a critical section?

For example, is this valid? CRITICAL_SECTION cs_A; CRITICAL_SECTION cs_b; ::InitializeCriticalSection( &cs_A ); ::InitializeCriticalSection( &cs_B ); ::EnterCriticalSection( &cs_A ); // First level /* do some stuff with A */ ::EnterCriticalSection( &cs_B ); // Second level /* do some stuff with A and B */ ::LeaveCriticalSection( &cs_B ); // Second level /*...

How do I call LocalFree()?

I have this piece of code HLOCAL localHandle; char *lpText; localHandle = LocalAlloc(LMEM_MOVEABLE, 40); if(localHandle) { lpText = (char*)LocalLock(localHandle); //Call LocalFree(localHandle) or LocalFree(lpText) ???? } Should I call LocalFree(localHandle); or LocalFree(lpText); ?...

How should I read the filename in FILE_NOTIFY_INFORMATION struct

I'm trying to monitor file changes but I am not really sure on how to read the filename in the FILE_NOTIFY_INFORMATION struct: HANDLE dwChangeHandles[2]; DWORD dwWaitStatus; wChangeHandles[0] = FindFirstChangeNotification(dirname.c_str(), FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE); if (dwChangeHandles[0] == INVALID_HANDLE_VALUE) printerr(__FILE__,__LINE__,"FindFirstChangeNotification function failed.\n"); ... if ((dwChangeHandles[0] == NULL) || (dwChangeHandles[1] == NULL)) //final validation printerr(__FILE__,__LINE__,"Unexpected...

How To Get Window handles In Mozilla Firefox

How to get handles of all the child windows in Mozilla firefox. Spy++ is showing only one class and window caption for all the windows. I tried using GetWindow and FindWindowEx but got nothing. I want to read URL from mozilla firefox.

Same version number for different Windows versions

In this page, there is something like this: Windows Server 2008 6.0 Windows Vista 6.0 GetVersionEx() returns the version number (i.e. 6.0), but as you can see, this number can map to two different Windows versions! So is there's a way to know exactly what Windows version I have?...


My UI is in a DLL. Right now, both the DLL and the EXE that uses it are compiled as console programs so I can use stdout and stderr for debugging and error reporting during development. One of the things is that I have an uninit() function that makes sure...

MoveFileEx() File removal on reboot

Currently I can remove a directory on reboot. Im currently doing this by using the MoveFileEx function along with passing the MOVEFILE_DELAY_UNTIL_REBOOTconstant. My question is if I have the following: Directory 1 and inside I have Directory 2... Directory 2 is unistalled which means the directory needs to be removed...

User process can't see global shared memory created by service

I have a Windows service (running in the system process) and a desktop application that need to share a configuration structure. The data originates in the app, but the user process doesn't have permission to create a global memory object so I create it when the service starts using CreateFileMapping()...

Issue finding exe path of all windows in python

I am using the code below to determine the foreground window and find the path for the .exe file that created it. hwnd = win32gui.GetForegroundWindow() _, pid = win32process.GetWindowThreadProcessId(hwnd) hndl = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, pid) path = win32process.GetModuleFileNameEx(hndl, 0) print path This workd for windows such as Google Chrome,...

Restarting a process from another process

I have two processes: ProcessA and ProcessB. When i launch my application, i call ProcessA which uses CreateProcess() to launch ProcessB. ProcessA is killed by ProcessB when my application receives command A. Likewise, ProcessB should relaunch ProcessA when it receives command B. Where i am stuck on is on the...

Get all supported FPS values of a camera in Microsoft Media Foundation

I want to get a list of all FPS values that my webcam supports. In How to Set the Video Capture Frame Rate msdn article it says that I can query the system for maximum and minimum supported FPS of a particular camera. It also says: The device might support...

Access std::map from different threads

I have read that std::map is not thread safe. So if I am accessing (read/write) the std::map from different threads, should I simply wrap the relevant code in a critical section? Note: I am using Visual C++ 2010....

Greedy algorithm: highest value first vs earliest deadline first

Assume we have a set of n jobs to execute, each of which takes unit time. At any time we can serve exactly one job. Job i, 1<=i<=n earns us a profit if and only if it is executed no later than its deadline. We can a set of jobs...

call Win32 API in flex to set Window Display Affinity

I have created a Flex Desktop Application with Adobe Air. I need to protect the application from being captured. By changing the window display affinity of the application, the application can be protected from being captured. How to use win API in flex? Is there any other way to protect...

how to change Text to Speech voice and how to insert characters into char array

I need to change the voie of the Text To Speech engine. when a menu is selected ID_SPEAK_PLAY I get the text of an edit box and simply read it. my situation can be solved in two ways : insert the XML code at the begining of ptrData without using...

Explain what problems could have this function (if any)

SCENARIO When P/Invoking, I thinked it could be a great idea to simplify/reduct tons of code by designing a generic function that calls the function, then it checks for the GetLastWin32Error I'm using this code: ''' <summary> ''' Invokes the specified encapsulated function, trying to provide a higher safety level...

C++ and WinApi - usage of GetWindowText() to get parameters for C++ code

I have coded some C++ console program which converts one filetype to another. I need to turn the console application into a window one. I have never made window applications. I have chosen WinApi, because I don't have much time and don't want to change IDE (DEV C++ 5.10), compiler/linker...

heap error after changing from new allocation to smartpointer

extern "C" int __stdcall calcA( LPCSTR SerialNumber, double Diameter, int Design, int FoilSpacing, double RotorSpeed, double Altitude, double SupplyAirInletTemperature, double SupplyAirInletMoistureContent, double ExhaustAirInletTemperature, double ExhaustAirInletMoistureContent, double SupplyAirOutletFlow, double ExhaustAirInletFlow, double PressureDifference, bool PurgingSector, double* PowerTotal, double* PowerSensibel, double* TemperatureEfficiency, double* HumidityEfficiency, double* SupplyAirOutletTemperature, double*...

How to execute a file with a different extension's associated application?

In my application, I would like to be able to execute a file with an arbitrary name and extension using the program associated with a different extension. For example, say I have a file called file.dat, but I wanted to open it with Notepad, as if it was named file.txt...

What is a runtime environment for supposedly “no-overhead” systems languages?

Specifically, I'm talking more about C++ and Rust than others. I don't understand how C++ has a "runtime" in the sense that Java and C# have a runtime--while Java and C# run on top of a virtual machine with its own encapsulated abstractions and such, I don't get how C++...

More convenient way to work with strings in winapi calls

I'm looking for more convenient way to work with std::String in winapi calls in Rust. Using rust v 0.12.0-nigtly with winapi 0.1.22 and user32-sys 0.1.1 Now I'm using something like this: use winapi; use user32; pub fn get_window_title(handle: i32) -> String { let mut v: Vec<u16> = Vec::new(); v.reserve(255); let...

How do I declare OutputDebugStringA without windows.h macros?

You know how Python has from urllib import *, but also offers from urllib import request, so you can just import that one symbol? Unfortunately C/C++ don't offer that but that's what I would like to do here: from windows.h import OutputDebugStringA, because all I need is that one function....

How to handle an event message while using chrome embedded framework (CEF)?

I'm using Chromium Embedded Framework(CEF) to develop a windows desktop application(using C++/Win32, No MFC). I have used the sample "cefsimple" project and extended on it till now. I have added "Handlers" for keyboard events etc. Everything works fine till now, I can get the handle of the browser window and...

C++ Windows API DlgDirList sometimes don't return the correct listing

I have 2 List Box, one always listing directories from a path and other listing the files from the selected directory. The first time i select a directory, the files are shown properly, but if i select another directory, it lists nothing. That's my current main.cpp, where all GUI stuff...

Win32 Message Pump and std::thread Used to Create OpenGL Context and Render

If I have a function that does the following: bool foo::init() { [Code that creates window] std::thread run(std::bind(&foo::run, this)); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } Where run is defined as: void foo::run() { [Code that creates initial opengl context] [Code that recreates window based on new...

Implementing callback function for dialog-based application

I was reading a very old tutorial on how to create a dialog-based GUI application in Visual C++ (source - in portuguese). Based on my weak knowledge on WinAPI programming I decided to modify the proposed code mainly to achieve two things: 1) Consistency with Unicode programming standard (using wWinMain...

How to create a submenu for a popup menu?

When I want to create a popup menu, I would use the CreatePopupMenu() function. But what if one of the popup menu items needs to have a submenu, should I also use CreatePopupMenu() to create the submenu, or should I use CreateMenu()?...