Wednesday, July 16, 2014

How to get system IP, Gateway, Subnet Mask address.

#include "winsock2.h"
#include "iphlpapi.h"
#include "stdio.h"
#include "stdlib.h"
#pragma comment(lib, "IPHLPAPI.lib")

#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))


int _tmain(int argc, _TCHAR* argv[])
{
   
    PIP_ADAPTER_INFO pAdapterInfo;
    PIP_ADAPTER_INFO pAdapter = NULL;
    DWORD dwRetVal = 0;
    UINT i;

/* variables used to print DHCP time info */
    struct tm newtime;
    char buffer[32];
    errno_t error;

    ULONG ulOutBufLen = sizeof (IP_ADAPTER_INFO);
    pAdapterInfo = (IP_ADAPTER_INFO *) MALLOC(sizeof (IP_ADAPTER_INFO));
    if (pAdapterInfo == NULL) {
        printf("Error allocating memory needed to call GetAdaptersinfo\n");
        return 1;
    }
// Make an initial call to GetAdaptersInfo to get
// the necessary size into the ulOutBufLen variable
    if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
        FREE(pAdapterInfo);
        pAdapterInfo = (IP_ADAPTER_INFO *) MALLOC(ulOutBufLen);
        if (pAdapterInfo == NULL) {
            printf("Error allocating memory needed to call GetAdaptersinfo\n");
            return 1;
        }
    }

    if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) {
        pAdapter = pAdapterInfo;
        while (pAdapter) {
            printf("\tComboIndex: \t5d\n", pAdapter->ComboIndex);
            printf("\tAdapter Name: \t%s\n", pAdapter->AdapterName);
            printf("\tAdapter Desc: \t%s\n", pAdapter->Description);
            printf("\tAdapter Addr: \t");
            for (i = 0; i < pAdapter->AddressLength; i++) {
                if (i == (pAdapter->AddressLength - 1))
                    printf("%.2X\n", (int) pAdapter->Address[i]);
                else
                    printf("%.2X-", (int) pAdapter->Address[i]);
            }
            printf("\tIndex: \t%d\n", pAdapter->Index);
            printf("\tType: \t");
            switch (pAdapter->Type) {
            case MIB_IF_TYPE_OTHER:
                printf("Other\n");
                break;
            case MIB_IF_TYPE_ETHERNET:
                printf("Ethernet\n");
                break;
            case MIB_IF_TYPE_TOKENRING:
                printf("Token Ring\n");
                break;
            case MIB_IF_TYPE_FDDI:
                printf("FDDI\n");
                break;
            case MIB_IF_TYPE_PPP:
                printf("PPP\n");
                break;
            case MIB_IF_TYPE_LOOPBACK:
                printf("Lookback\n");
                break;
            case MIB_IF_TYPE_SLIP:
                printf("Slip\n");
                break;
            default:
                printf("Unknown type %ld\n", pAdapter->Type);
                break;
            }

            printf("\tIP Address: \t%s\n",
                   pAdapter->IpAddressList.IpAddress.String);
            printf("\tIP Mask: \t%s\n", pAdapter->IpAddressList.IpMask.String);

            printf("\tGateway: \t%s\n", pAdapter->GatewayList.IpAddress.String);
            printf("\t***\n");

            if (pAdapter->DhcpEnabled) {
                printf("\tDHCP Enabled: Yes\n");
                printf("\t  DHCP Server: \t%s\n",
                       pAdapter->DhcpServer.IpAddress.String);

                printf("\t  Lease Obtained: ");
                /* Display local time */
                error = _localtime32_s(&newtime, (__time32_t*) &pAdapter->LeaseObtained);
                if (error)
                    printf("Invalid Argument to _localtime32_s\n");
                else {
                    // Convert to an ASCII representation
                    error = asctime_s(buffer, 32, &newtime);
                    if (error)
                        printf("Invalid Argument to asctime_s\n");
                    else
                        /* asctime_s returns the string terminated by \n\0 */
                        printf("%s", buffer);
                }

                printf("\t  Lease Expires:  ");
                error = _localtime32_s(&newtime, (__time32_t*) &pAdapter->LeaseExpires);
                if (error)
                    printf("Invalid Argument to _localtime32_s\n");
                else {
                    // Convert to an ASCII representation
                    error = asctime_s(buffer, 32, &newtime);
                    if (error)
                        printf("Invalid Argument to asctime_s\n");
                    else
                        /* asctime_s returns the string terminated by \n\0 */
                        printf("%s", buffer);
                }
            } else
                printf("\tDHCP Enabled: No\n");

            if (pAdapter->HaveWins) {
                printf("\tHave Wins: Yes\n");
                printf("\t  Primary Wins Server:    %s\n",
                       pAdapter->PrimaryWinsServer.IpAddress.String);
                printf("\t  Secondary Wins Server:  %s\n",
                       pAdapter->SecondaryWinsServer.IpAddress.String);
            } else
                printf("\tHave Wins: No\n");
            pAdapter = pAdapter->Next;
            printf("\n");
        }
    } else {
        printf("GetAdaptersInfo failed with error: %d\n", dwRetVal);

    }
    if (pAdapterInfo)
        FREE(pAdapterInfo);

    return 0;

   
}

Friday, June 21, 2013

Build .Net application which works on multiple .net framework...

Step 1: Create a .net application and change the .Net Target framework to 3.5.
Step 2: In app.config file enter both .net framework 4.0 and 3.5 like below







Tuesday, February 14, 2012

UCHAR array ( or BYTE array ) to variant type

UCHAR szBuf[8];
szBuf50[0] = 0;
szBuf50[1] = 0;
szBuf50[2] = 0;
szBuf50[3] = 1;
szBuf50[4] = 0;
szBuf50[5] = 0;
szBuf50[6] = 3;
szBuf50[7] = 231;

VARIANT data;
SAFEARRAY * safeArray;
UCHAR *safeArrayData;
safeArray = SafeArrayCreateVector( VT_UI1, 0, 8 );

SafeArrayAccessData( safeArray, ( void ** ) &safeArrayData );
CopyMemory( safeArrayData, szBuf, 8 );
SafeArrayUnaccessData( safeArray );

VariantInit( &data );
data.vt = VT_ARRAY | VT_UI1;
data.parray = safeArray;
//after using the data delete it if no longer needed..
VariantClear( &data );

Friday, January 6, 2012

How ro run build.xml using ant

Step 1:

Install Ant ( or copy Ant folder to c: )

Step 2:

Install Java sdk

Then system user environmetal variable set the following environmental variable

ANT_HOME c:\Ant
JAVA_HOME C:\Program Files\Java\jdk1.6.0_27

in system environmental variable "Path" include this value as well C:\Ant\bin

Step 3:

Now in coomand prompt type Example => ant Install32

( Install32 is taget name in build.xml )

Thursday, December 1, 2011

Enumurating all names and values of registry key

HKEY hKey = NULL;
if( RegOpenKeyEx(HKEY_LOCAL_MACHINE,L"SOFTWARE\\Hewlett-Packard\\LaserJetService\\{488E28CB-3EAC-4EF3-8ACA-EE161849B618}",0,KEY_READ,&hKey) == ERROR_SUCCESS)
{

DWORD cSubKeys; // number of subkeys
DWORD cbMaxSubKey; // longest subkey size
DWORD cchMaxClass; // longest class string
DWORD cValues = 0; // number of values for key
DWORD cchMaxValue; // longest value name
DWORD cbMaxValueData; // longest value data
DWORD cbSecurityDescriptor; // size of security descriptor
FILETIME ftLastWriteTime; // last write time

DWORD j;
DWORD retValue;

// Get the class name and the value count.
retValue = RegQueryInfoKey(hKey, // key handle
NULL, // buffer for class name
NULL, // length of class string
NULL, // reserved
&cSubKeys, // number of subkeys
&cbMaxSubKey, // longest subkey size
&cchMaxClass, // longest class string
&cValues, // number of values for this key
&cchMaxValue, // longest value name
&cbMaxValueData, // longest value data
&cbSecurityDescriptor, // security descriptor
&ftLastWriteTime); // last write time

// Enumerate the child keys, until RegEnumKeyEx fails.

TCHAR *achValueName = new TCHAR[cchMaxValue+1];
if (!achValueName) return;

TCHAR *achValueData = new TCHAR[cbMaxValueData+1];
if (!achValueData)
{
delete [] achValueName;
return;
}


// Enumerate the key values.

if (cValues && cValues!=-1 && retValue==ERROR_SUCCESS)
{
for (j = 0, retValue = ERROR_SUCCESS; j < cValues; j++)
{
DWORD cchValueName = cchMaxValue + 1;
DWORD cchValueData = cbMaxValueData + 1;
DWORD dwType;

achValueName[0] = _T('\0');
achValueData[0] = _T('\0');

retValue = RegEnumValue(hKey, j, achValueName,
&cchValueName,
NULL,
&dwType,
(LPBYTE) achValueData,
&cchValueData);

if (retValue == ERROR_SUCCESS)
{
int n = 8;
}

}

} // end if (cValues && cValues!=-1)

if (achValueData)
delete [] achValueData;
if (achValueName)
delete [] achValueName;

RegCloseKey(hKey);
}

Friday, October 21, 2011

Convert UNICODE to ANSI...and UTF-8 to UNICODE

string sPath;

sPath = ConvertAnsiToUnicode(argv[0],_tcslen(argv[0]));

------------------------

string ConvertAnsiToUnicode(wchar_t *szString,int nSzie)
{
int cbMultiByte = ::WideCharToMultiByte(CP_UTF8, 0, szString, nSzie+1, NULL, 0,
NULL, NULL);

char* pMultiByteStr = NULL;
string result;

if (cbMultiByte > 0)

{

pMultiByteStr = new char[cbMultiByte];

cbMultiByte = ::WideCharToMultiByte(CP_UTF8, 0, szString, nSzie+1, pMultiByteStr,
cbMultiByte, NULL, NULL);

if (cbMultiByte > 0 && pMultiByteStr[cbMultiByte-1] == NULL)
{
cbMultiByte--;
}


if (cbMultiByte > 0)
{
result.assign(pMultiByteStr, cbMultiByte);
}

delete[] pMultiByteStr;

}

return result;
}
----------------------------------------------------------------------------------------------------------------

std::wstring CStringUtils::WStringFromChar(const char* pSource, int cchSource)
{
    std::wstring result;
    if (pSource != NULL)
    {
        if (cchSource == -1)
        {
            cchSource = (int)strlen(pSource) + 1;
        }
        int cchWideChar = ::MultiByteToWideChar(CP_UTF8, 0, pSource, cchSource, NULL, 0);
        if (cchWideChar > 0)
        {
            wchar_t* pWideCharStr = NULL;
            try
            {
                pWideCharStr = new wchar_t[cchWideChar];
                cchWideChar = ::MultiByteToWideChar(CP_UTF8, 0, pSource, cchSource, pWideCharStr, cchWideChar);
                if (cchWideChar > 0 && pWideCharStr[cchWideChar-1] == NULL)
                {
                    cchWideChar--;
                }
                if (cchWideChar > 0)
                {
                    result.assign(pWideCharStr, cchWideChar);
                }
            }
            catch (...)
            {
            }
            delete[] pWideCharStr;
        }
    }
    return result;
}

Monday, August 29, 2011

WinSock server..

#include "stdafx.h"
#include
#include

#include
#include


void ServerThread(void* pParam)
{
//A SOCKET is simply a typedef for an unsigned int.
//In Unix, socket handles were just about same as file
//handles which were again unsigned ints.
//Since this cannot be entirely true under Windows
//a new data type called SOCKET was defined.

FILE *pFile;
struct stat fileinfo;

SOCKET server;

//WSADATA is a struct that is filled up by the call
//to WSAStartup
WSADATA wsaData;

//The sockaddr_in specifies the address of the socket
//for TCP/IP sockets. Other protocols use similar structures.
sockaddr_in local;

//WSAStartup initializes the program for calling WinSock.
//The first parameter specifies the highest version of the
//WinSock specification, the program is allowed to use.
int wsaret=WSAStartup(0x101,&wsaData);

//WSAStartup returns zero on success.
//If it fails we exit.
if(wsaret!=0)
{
// return 0;
}

//Now we populate the sockaddr_in structure
local.sin_family=AF_INET; //Address family
local.sin_addr.s_addr = inet_addr("127.0.0.1"); // 16.182.218.213"); //16.182.218.240
local.sin_port = htons(631);

//the socket function creates our SOCKET
server=socket(AF_INET,SOCK_STREAM,0);

//If the socket() function fails we exit
if(server==INVALID_SOCKET)
{
// return 0;
}

//bind links the socket we just created with the sockaddr_in
//structure. Basically it connects the socket with
//the local address and a specified port.
//If it returns non-zero quit, as this indicates error
if(bind(server,(sockaddr*)&local,sizeof(local))!=0)
{
// return 0;
}

//listen instructs the socket to listen for incoming
//connections from clients. The second arg is the backlog
if(listen(server,10)!=0)
{
// return 0;
}

//we will need variables to hold the client socket.
//thus we declare them here.
SOCKET client;
sockaddr_in from;
int fromlen=sizeof(from);

while(true)//we are looping endlessly
{
char temp[4096];

client=accept(server,
(struct sockaddr*)&from,&fromlen);

int bytes = 0;
int h = 0;
do
{
bytes = 0;
memset(&temp,0,4096);
bytes = recv(client,temp,4096,0);
if (bytes<4096) break;


}while ( bytes > 0 );

char* szFileBuf= NULL;
bytes=0;
const char filename[] = "c:\\Result_PrintJob.txt";
FILE *file;
struct stat fileinfo;
if (filename != NULL)
{
if (stat(filename, &fileinfo))
{
return ;
}
if ((file = fopen(filename, "rb")) == NULL)
{
return ;
}

rewind(file);
szFileBuf = new char[(size_t)fileinfo.st_size];
bytes = fread(szFileBuf, 1, (size_t)fileinfo.st_size, file);

if (file)
fclose(file);
h = send(client,szFileBuf,bytes,0);

break;
}


// cout << "Connection from " << inet_ntoa(from.sin_addr) <<"\r\n";

//close the client socket
closesocket(client);

}

//closesocket() closes the socket and releases the socket descriptor
closesocket(server);

//originally this function probably had some use
//currently this is just for backward compatibility
//but it is safer to call it as I still believe some
//implementations use this to terminate use of WS2_32.DLL
WSACleanup();

// return 0;
}



int _tmain(int argc, _TCHAR* argv[])
{
int nRetCode = 0;

_beginthread( ServerThread, 0, NULL );

while(_getch()!=27);

return nRetCode;

}