Circular Buffer

I have created a program using heap memory to implement circular buffer. The following is the code of the program.

 

// testCircularBuffer.cpp : Defines the entry point for the console application.
//

#include<iostream>

#include “stdio.h”
#include “stdlib.h”
#include “string.h”
#include<Windows.h>

#define LONG int
#define PBYTE char *

#define TRUE 1
#define FALSE 0

static LONG m_ReadHanlde;
static LONG m_WriteHanlle;
static PBYTE pMemBuffer;
static int memBufWrap ;// buffer wrap around

#define MIN_CHUNK_SIZE 1024 * 1024
int CIRCULAR_BUFFER_SIZE = 5 * MIN_CHUNK_SIZE; // size in MB

int InitCircularMemBuffer()
{

pMemBuffer = NULL;
m_ReadHanlde = 0;
m_WriteHanlle = 0;
memBufWrap = 0;

pMemBuffer = (char*) malloc(CIRCULAR_BUFFER_SIZE);
if(pMemBuffer == NULL){
return -1;
}

return 0;
}

int ReleaseCircularMemBuffer()
{

if(pMemBuffer != NULL){
free( pMemBuffer);
pMemBuffer = NULL;
}

return 0;
}

LONG GetCircularMemBufferSpace()
{
LONG lMemDist = 0;

if(pMemBuffer == NULL)
return 0;

//if(m_WritePtr == 0 && m_ReadPtr == 0)
if((m_WriteHanlle == m_ReadHanlde)&& (!memBufWrap))
{

return CIRCULAR_BUFFER_SIZE;
}

if(m_WriteHanlle > m_ReadHanlde)
{
lMemDist = (CIRCULAR_BUFFER_SIZE – m_WriteHanlle) + m_ReadHanlde;
}
else
{
lMemDist = m_ReadHanlde – m_WriteHanlle;
}

return lMemDist;
}

LONG GetCircularMemBufferArea()
{
LONG lmemArea = 0;

if(pMemBuffer == NULL)
return 0;

if(m_WriteHanlle == m_ReadHanlde && (!memBufWrap))
{

return 0;
}

if(m_WriteHanlle > m_ReadHanlde)
{
lmemArea = m_WriteHanlle – m_ReadHanlde;
}
else
{
lmemArea = (CIRCULAR_BUFFER_SIZE – m_ReadHanlde) + m_WriteHanlle;
}

return lmemArea;
}

int ResetCiruclarMemBuffer()
{
int MaxSecondCnt=10,i;

m_ReadHanlde = 0;
m_WriteHanlle = 0;
memBufWrap = 0;

return TRUE;
}

int ReadCircularMemBuffer(PBYTE pBuff, LONG lSize)
{
LONG lDist;

for(;;)
{
if(GetCircularMemBufferArea() >= lSize)
break;
else
{
Sleep(100);

}

}

if( ( m_ReadHanlde + lSize) > CIRCULAR_BUFFER_SIZE )
{
lDist = CIRCULAR_BUFFER_SIZE – m_ReadHanlde;
memcpy(pBuff, (pMemBuffer + m_ReadHanlde), lDist);
memcpy(pBuff + lDist, pMemBuffer, lSize – lDist);
m_ReadHanlde = lSize – lDist;
memBufWrap =0; // read also wrap around
}
else
{
memcpy(pBuff, (pMemBuffer + m_ReadHanlde), lSize);
m_ReadHanlde += lSize;
}

return lSize;
}

int WriteCircularMemBuffer(PBYTE pBuff, LONG lSize)
{
int dwDist;
//printf(“WriteBuffer+\n”);
if(pMemBuffer == NULL)
return FALSE;

//wait for enough space
for(;;)
{
if(GetCircularMemBufferSpace() >= lSize){
break;

}
else
{
Sleep(1);
}
}

if( ( m_WriteHanlle + lSize) > CIRCULAR_BUFFER_SIZE)
{

dwDist = CIRCULAR_BUFFER_SIZE – m_WriteHanlle;
memcpy( (pMemBuffer + m_WriteHanlle), pBuff,dwDist);

memcpy(pMemBuffer, (pBuff + dwDist), lSize – dwDist);
m_WriteHanlle = lSize – dwDist;
memBufWrap = 1;// the buffer just wrap around

return TRUE;
}

memcpy( (pMemBuffer + m_WriteHanlle), pBuff,lSize);
m_WriteHanlle += lSize;

return TRUE;
}

char testWriteBuf[5*MIN_CHUNK_SIZE+1];
char testReadBuf[5*MIN_CHUNK_SIZE+1];

int main()
{

InitCircularMemBuffer();

printf(“Free Mem %d and data size %d in buff m_WriteHandle %d m_ReadHanlde %d\n”,GetCircularMemBufferSpace(),GetCircularMemBufferArea(),m_WriteHanlle,m_ReadHanlde);
if(!WriteCircularMemBuffer(testWriteBuf, MIN_CHUNK_SIZE))
printf(“Write error\n”);
printf(“Free Mem %d and Data size %d avaliable in buff m_WritePtr %d m_ReadPtr %d\n”,GetCircularMemBufferSpace(),GetCircularMemBufferArea(),m_WriteHanlle,m_ReadHanlde);

if(!ReadCircularMemBuffer(testReadBuf, MIN_CHUNK_SIZE))
printf(“Read memory buffer error\n”);

}

Working with memory

I have created a program in which i have handled a memory allocated from heap. In this program i have created a memory of specific size form heap and storing data in it. When the memory is full then i reset it from start and storing data again in the memory. The following is the complete code of the program. 

 

// testMemory.cpp : Defines the entry point for the console application.
//

#include<stdio.h>
#include<iostream>

using namespace std;

char *startOfMemory;
char *pMemory;

int main(void){

pMemory = (char *)malloc(256);
startOfMemory = pMemory;
int countMem = 0;
char *str = strdup(“This is just test msg”);
int len = strlen(str);
int count = 0;
while(count<1000){

if (countMem + len > 256){
pMemory = startOfMemory;
printf(“Mem is full now set to start\n”);
countMem = 0;
}
memcpy(pMemory,str,len);
pMemory = pMemory + len;
countMem = countMem + len;
printf(“Mem Size:%d\n”,countMem);

count = count + 1;
}
pMemory = startOfMemory;

free(pMemory);
pMemory = NULL;

getchar();
return 0;
}

Encoding and decoding of Struct

I have created a program in which i have encode and decode the struct. This is required when sending data using network. The following is the code of the program.

// testStructEnDec.cpp : Defines the entry point for the console application.
//

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>

using namespace std;

typedef struct ipV4{
char *strIP;
}tIpV4;

typedef struct IPList{
int num;
int port;
tIpV4 objIPList[20];
}tRemoteIPList;

size_t encodeRemoteIP(tRemoteIPList* objIPList, unsigned char** buf);
tRemoteIPList* decodeIP(const unsigned char* buf, const size_t bufSize);

int main(void){
tRemoteIPList objList;

objList.num = 3;
objList.port = 80;
objList.objIPList[0].strIP = strdup(“192.168.1.1”);
objList.objIPList[1].strIP = strdup(“192.168.1.2”);
objList.objIPList[2].strIP = strdup(“192.168.1.10”);
unsigned char *buf;
size_t bufSize = encodeRemoteIP(&objList,&buf);

tRemoteIPList* objIP = decodeIP(buf,bufSize);
printf(“Port:%d”,objIP->port);
for(int count = 0;count<objIP->num;count++){
printf(“IP:%s\n”,objIP->objIPList[count].strIP);

}

getchar();
return 0;
}

size_t encodeRemoteIP(tRemoteIPList* objIPList, unsigned char** buf)
{
int count;
size_t total_size = 0;
if (!objIPList)
{
return 0;
}
total_size = total_size + sizeof(size_t) + sizeof(size_t); // no of ips.

for(count = 0;count<objIPList->num;count++){
total_size = total_size + strlen(objIPList->objIPList[count].strIP) + sizeof(size_t)+sizeof(size_t);
}

*buf = (unsigned char *)calloc(1,total_size);
if (*buf)
{
size_t offset = 0;
size_t ipLen;
size_t numIp = htonl(objIPList->num);
size_t port = htonl(objIPList->port);

memcpy(*buf + offset, &numIp,sizeof(numIp)); offset += sizeof(numIp);
memcpy(*buf + offset, &port,sizeof(port)); offset += sizeof(port);
for(count = 0;count<objIPList->num;count++){
ipLen = strlen(objIPList->objIPList[count].strIP);
ipLen = htonl(ipLen);
memcpy(*buf + offset, &ipLen,sizeof(size_t)); offset += sizeof(ipLen);
memcpy(*buf + offset, objIPList->objIPList[count].strIP,ipLen); offset += ipLen;
}
}

return total_size;

}

tRemoteIPList* decodeIP(const unsigned char* buf, const size_t bufSize)
{
tRemoteIPList *objIP;

if(buf!= NULL){
objIP = (tRemoteIPList *)calloc(1, sizeof(tRemoteIPList));

if(objIP !=NULL){
size_t numIP = 0;
size_t port;
size_t offset = 0;
size_t ipLen;
unsigned int count = 0;
memcpy(&numIP, buf + offset, sizeof(numIP));
numIP = ntohl(numIP);
offset += sizeof(numIP);
objIP->num = numIP;

memcpy(&port, buf + offset, sizeof(port));
port = ntohl(port);
offset += sizeof(port);
objIP->port = port;

for(count = 0;count<numIP;count++){
memcpy(&ipLen, buf + offset, sizeof(ipLen));
ipLen = ntohl(ipLen);
offset += sizeof(ipLen);
objIP->objIPList[count].strIP = (char *)calloc(1,ipLen + 1);
memcpy(objIP->objIPList[count].strIP,buf+offset,ipLen);
offset +=ipLen;

}

}
}

return objIP;
}

Array of Pointer to Pointer

I have created a program in which i have used array of pointer to pointers. The following is the complete code. 

// testArrayOfPointers.cpp : Defines the entry point for the console application.
//

#include<conio.h>
#include<iostream>

using namespace std;

typedef unsigned char ** arrayofPointerToPointer[5];

arrayofPointerToPointer pointerToPointerList;
unsigned char **pPointerArray;

int main(void){

for(int count = 0;count<5;count++){
pointerToPointerList[count] = NULL;
}
pPointerArray = (unsigned char **)malloc(5 * sizeof(unsigned char **));
pointerToPointerList[0] = pPointerArray;
char *strName1 = strdup(“Jawad1”);
char *strName2 = strdup(“Jawad2”);
char *strName3 = strdup(“Jawad3”);
char *strName4 = strdup(“Jawad4”);
pPointerArray[0] = (unsigned char*)strName1;
pPointerArray[1] = (unsigned char*)strName2;
pPointerArray[2] = (unsigned char*)strName3;
pPointerArray[3] = (unsigned char*)strName4;

unsigned char **pTempPointerArray = pointerToPointerList[0];

for(int i=0;i<4;i++){
printf(“My name:%s\n”,pTempPointerArray[i]);
}

getchar();
return 0;
}

 

Array and pointers

I have created a program in  which i have worked with arrays like 1 dim, 2 dim and 3 dim . In this program i have accessed elements of array using different methods. The program is as follows.

// testArrays.cpp : Defines the entry point for the console application.
//

#include<stdio.h>
#include<iostream>

int main(void){

//single dimension array
int a[5] = {1,2,3,4,5};
//pointer to store the starting address of array
int *ptr;
ptr = a;
//a[1] or *(a + 1) — 1 read operation
//ptr[1] or *(ptr + 1)—2 read operation
printf(“1st element a[1]:%d and prt:%d\n”,a[1],*(ptr +1)) ;

//two dimension array
int a2d[2][5] = {{1,2,3,4,5},{5,6,7,8,9}};
//pointer to two dimesnion array.
int (*ptr2D)[5];

ptr2D = a2d;

printf(“a2d[1][4]:%d *(*(a2d+1)+4):%d\n”,a2d[1][4],*(*(a2d+1)+4));
printf(“dim-ptr2D[1][4]:%d *(*(ptr2D+1)+4):%d\n”,ptr2D[1][4],*(*(ptr2D+1)+4));

//three dimenison array
int a3D[2][3][4] = { { {1, 2, 3, 4}, {4, 5, 6, 7}, {8, 9, 10,11} },
{ {12, 13, 14, 15}, {16, 17, 18, 19}, {20, 21, 22, 23} } };

int (* ptr3D)[3][4];
ptr3D = a3D;

printf(“a3D[1][2][3]:%d *(*(*(a3D+1)+2)+3):%d\n”,a3D[1][2][3], *(*(*(a3D+1)+2)+3));
printf(“ptr3D[1][2][3]:%d *(*(*(ptr3D+1)+2)+3):%d\n”,ptr3D[1][2][3], *(*(*(ptr3D+1)+2)+3));

//pointer to three dimensional array

getchar();
}

 

Low and Hi Word modificaion

I have created a program in which I have modified the Low Word and High Word of integer. Then these low and high words are obtained from integer type. The following is the code of program.

// testTypeManipulation.cpp : Defines the entry point for the console application.
//

#include<stdio.h>
#include<iostream>

int replaceLowWordFromInt(int x, int n, int c) {
int mask = 0xffff << (n << 3);
int shift = (c << (n << 3));
return (~mask & x) | shift;
}

int replaceHiWordFromInt(int x, int n, int c) {
x = (x & 0xFFFF) | (c << 16);
return x;
}

short getLowWordFromInt(int value)
{

return (value & 0xFFFF);
}

short getHiWordFromInt(int value)
{
return ((value & 0xFFFF0000)>>16);
}

int main(void){

int Lowval = 500;
int Hival = 600;
int data = 0;
short lowWord;
short hiWord;
//Modificaion in LO and HI Word of integer.
data = replaceLowWordFromInt(data,0,Lowval);
data = replaceHiWordFromInt(data,0,Hival);
printf(“After modificaion:%d\n”,data);
lowWord = getLowWordFromInt(data);
hiWord = getHiWordFromInt(data);
printf(“Low Word:%d and High Word:%d\n”,lowWord,hiWord);
int combine = ((hiWord<<16) | ((lowWord) & 0xffff));
printf(“Combine :%d\n”,combine);
getchar();
return 0;
}

 

Network Info Application (Ethernet Card)

I have created an application which obtains the network interface information like IP address assigned to the card, interface friendly name and it is currently connected with the network or not.  The code is as follows;

// testLANInfo.cpp : Defines the entry point for the console application.
//

#include<stdio.h>
#include<iostream>
#include <vector>
#include <winsock2.h>
#include <iphlpapi.h>

#pragma comment(lib, “IPHLPAPI.lib”)
using namespace std;

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

typedef struct networkInterfaceDetails{
string interfaceName;
string strIP;
int isConnectedOrDisConnected;
}tNetworkInterfaceDetails;

int getNetworkInterfaceInfo(vector<tNetworkInterfaceDetails *> &objInterfaceDetails)
{
DWORD dwSize = 0;
DWORD dwRetVal = 0;

unsigned int i = 0;
// Set the flags to pass to GetAdaptersAddresses
ULONG flags = GAA_FLAG_INCLUDE_PREFIX;

// default to unspecified address family (both)
ULONG family = AF_UNSPEC;

LPVOID lpMsgBuf = NULL;

PIP_ADAPTER_ADDRESSES pAddresses = NULL;
ULONG outBufLen = 0;

PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
family = AF_INET;

outBufLen = sizeof (IP_ADAPTER_ADDRESSES);
pAddresses = (IP_ADAPTER_ADDRESSES *) MALLOC(outBufLen);

// Make an initial call to GetAdaptersAddresses to get the
// size needed into the outBufLen variable
if (GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen)
== ERROR_BUFFER_OVERFLOW) {
FREE(pAddresses);
pAddresses = (IP_ADAPTER_ADDRESSES *) MALLOC(outBufLen);
}

if (pAddresses == NULL) {
//DEBUG(“Memory allocation failed for IP_ADAPTER_ADDRESSES struct\n”);
return 1;
//exit(1);
}

dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);

if (dwRetVal == NO_ERROR) {
// If successful, output some information from the data we received
pCurrAddresses = pAddresses;
while (pCurrAddresses) {

switch (pCurrAddresses->IfType) {
case IF_TYPE_ETHERNET_CSMACD:
{
char conBuffer[100];
int ret;
string conStr;
string IPstr;
ret = wcstombs ( conBuffer, pCurrAddresses->FriendlyName, sizeof(conBuffer) );
tNetworkInterfaceDetails *objEthernetInfo = new tNetworkInterfaceDetails;
objEthernetInfo->interfaceName = conStr;
objEthernetInfo->strIP = IPstr;

switch (pCurrAddresses->OperStatus) {
case IfOperStatusUp:
objEthernetInfo->isConnectedOrDisConnected = 1;
break;
case IfOperStatusDown:
objEthernetInfo->isConnectedOrDisConnected = 0;
break;
default:
objEthernetInfo->isConnectedOrDisConnected = 0;
}

objInterfaceDetails.push_back(objEthernetInfo);
break;
}

pCurrAddresses = pCurrAddresses->Next;
}
}
}else {
if (dwRetVal == ERROR_NO_DATA)
return 1;
else {

if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwRetVal, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) & lpMsgBuf, 0, NULL)) {
LocalFree(lpMsgBuf);
FREE(pAddresses);
return 1;
}
}
}

FREE(pAddresses);

return 0;

} //end getNetworkInterfaceInfo

int main(void){

vector<tNetworkInterfaceDetails *> objInterfaceInfo;
getNetworkInterfaceInfo(objInterfaceInfo);

for(int countInterfaces = 0;countInterfaces<objInterfaceInfo.size();countInterfaces++){
tNetworkInterfaceDetails *objInfo = (tNetworkInterfaceDetails *)objInterfaceInfo.at(countInterfaces);

printf(“Interface Friendly name:%s\n”,objInfo->interfaceName);
printf(“Interface IP:%s\n”,objInfo->strIP);
printf(“Connection Status:”);
if(objInfo->isConnectedOrDisConnected == 1){
printf(“Connected\n”);
}
else{
printf(“Not Connected\n”);
}
}
getchar();
return 0;
}

Thread De-Allocation

I have created functions for thread creating and its successful de allocation in DLL. Usually when program is created having threads, thread de allocation creates issues when not properly handled. In my program I have created a mechanism of proper de allocation of thread.

The code of DLL is as follow:

 // dllmain.h

 #ifndef __DLL_MAIN_H__

#define __DLL_MAIN_H__

 #ifdef WIN32

#define EXPORT extern __declspec(dllexport)

#else

#define EXPORT extern

#endif

 

typedef void (* threadEntryFunction)(void *pArgs);

 #endif

 // dllmain.cpp : Defines the entry point for the DLL application.

 

#include<Windows.h>

#include “dllmain.h”

#include<stdio.h>

static BOOL isThreadRunning = FALSE;

typedef struct taskInfo

{

    HANDLE taskHandle;

    threadEntryFunction taskEntryFunction;

    void *pArgs;

} taskInfo;

 

BOOL APIENTRY DllMain( HMODULE hModule,

                       DWORD  ul_reason_for_call,

                       LPVOID lpReserved

                                   )

{

       switch (ul_reason_for_call)

       {

       case DLL_PROCESS_ATTACH:

       case DLL_THREAD_ATTACH:

       case DLL_THREAD_DETACH:

       case DLL_PROCESS_DETACH:

              break;

       }

       return TRUE;

}

 

static unsigned __stdcall SystemTaskEntryPoint(taskInfo * pTask)

{

 

    /* call the task user entry function – this will not return until task

       execution is finished */

    pTask->taskEntryFunction(pTask->pArgs);

   

    /* retruned from user function – close the task and end the thread */

    if(pTask->taskHandle)

    {

 

        CloseHandle(pTask->taskHandle);

        pTask->taskHandle = NULL;

 

        free(pTask);

              printf(“Thread is deAllocated successfully”);

    }

   

    return(0);

}

 

void createTask(HANDLE *pTaskHandle,threadEntryFunction entryFunction,void *pArgs)

{

       taskInfo *objTaskInfo;

       DWORD threadId;

       objTaskInfo =(taskInfo *) malloc(sizeof(taskInfo));

 

    objTaskInfo->pArgs = pArgs;

    objTaskInfo->taskEntryFunction = entryFunction;

 

       objTaskInfo ->taskHandle = CreateThread(0, 0,(LPTHREAD_START_ROUTINE) SystemTaskEntryPoint,(PVOID)objTaskInfo, 0, &threadId);

       *pTaskHandle = objTaskInfo->taskHandle;

 

}

void testThread(void *pArgs){

       char *str = (char *)pArgs;

       int count = 0;

       printf(“Thread started ad str:%s\n”,str);

       while(isThreadRunning){

              printf(“Thread is running with count:%d\n”,count);

              count = count + 1;

       }

 

}

extern “C” {

 

EXPORT int test_startTask(void)

{

       AllocConsole();

                     AttachConsole( GetCurrentProcessId() ) ;

                     freopen( “CON”, “w”, stdout ) ;

 

       HANDLE threadHandle;

       char *str= “This is test msg\n”;

       isThreadRunning = TRUE;

       createTask(&threadHandle,testThread,str);

    return TRUE;

}

 

EXPORT int test_StopTask(void)

{

       isThreadRunning = FALSE;

      

  return TRUE;

}

}

Network Statistics Application

I have created an application using network APIs of windows to obtain the list applications using network both WIFI and LAN for TCP data type.  The information contains local IP, local port, remote IP, remote port,  application name and connection status.

The following windows APIs are used in my project;

GetExtendedTcpTable function

http://msdn.microsoft.com/en-us/library/windows/desktop/aa365928(v=vs.85).aspx

MIB_TCPTABLE_OWNER_PID structure

http://msdn.microsoft.com/en-us/library/windows/desktop/aa366921(v=vs.85).aspx

CreateToolhelp32Snapshot function

http://msdn.microsoft.com/en-us/library/windows/desktop/ms682489(v=vs.85).aspx

Process32First function

http://msdn.microsoft.com/en-us/library/windows/desktop/ms684834(v=vs.85).aspx

PROCESSENTRY32 structure

http://msdn.microsoft.com/en-us/library/windows/desktop/ms684839(v=vs.85).aspx

Process32Next function

http://msdn.microsoft.com/en-us/library/windows/desktop/ms684836(v=vs.85).aspx

Complete code of application:

 #include<stdio.h>

#include<iostream>
#include<vector>

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

#include <tlhelp32.h>
using namespace std;

#pragma comment(lib, “IPHLPAPI.lib”)

typedef enum tcpConnectionState{eMIB_TCP_STATE_CLOSED = 1,
eMIB_TCP_STATE_LISTEN = 2,
eMIB_TCP_STATE_SYN_SENT = 3,
eMIB_TCP_STATE_SYN_RCVD = 4,
eMIB_TCP_STATE_ESTAB = 5,
eMIB_TCP_STATE_FIN_WAIT1 = 6,
eMIB_TCP_STATE_FIN_WAIT2 = 7,
eMIB_TCP_STATE_CLOSE_WAIT = 8,
eMIB_TCP_STATE_CLOSING = 9,
eMIB_TCP_STATE_LAST_ACK = 10,
eMIB_TCP_STATE_TIME_WAIT = 11,
eMIB_TCP_STATE_DELETE_TCB = 12} tTcpConnectionState;

typedef struct networkProcessInfo{
DWORD pid;
char *processName;
DWORD state;
char localIP[16];
unsigned short localPort;
char remoteIP[16];
unsigned short remotePort;
}tNetworkProcessInfo;

vector<tNetworkProcessInfo *> objNetworkProcessInfo;
void getAllActiveTCPConnection();
char * GetNameByPID(DWORD processPid);

int main(void)
{
getAllActiveTCPConnection();
printf(“No of active TCP connections\n”);
for(unsigned int i=0;i<objNetworkProcessInfo.size();i++){
tNetworkProcessInfo *objInfo = (tNetworkProcessInfo *)objNetworkProcessInfo.at(i);
printf(“Process Name:%s\n”,objInfo->processName);
printf(“Connection Status:”);
switch(objInfo->state){
case eMIB_TCP_STATE_LISTEN:
printf(“Listen\n”);
break;
case eMIB_TCP_STATE_ESTAB:
printf(“Established\n”);
break;
case eMIB_TCP_STATE_CLOSING:
printf(“Closing\n”);
break;
}
printf(“Local IP:%s and local Port:%d\n”,objInfo->localIP,objInfo->localPort);
printf(“Remote IP:%s and Remote Port:%d\n”,objInfo->remoteIP,objInfo->remotePort);
}
getchar();
return 0;
}

void getAllActiveTCPConnection(){
// See msdn

// ulAf value TableClass value pTcpTable structure
// AF_INET TCP_TABLE_OWNER_PID_ALL -> MIB_TCPTABLE_OWNER_PID
// AF_INET6 TCP_TABLE_OWNER_PID_ALL -> MIB_TCP6TABLE_OWNER_PID

// –> only AF_INET(IPv4)!! <–

vector<unsigned char> buffer;
DWORD dwSize = sizeof(MIB_TCPTABLE_OWNER_PID);
DWORD dwRetValue = 0;

// repeat till buffer is big enough
do
{
buffer.resize(dwSize, 0);
dwRetValue = GetExtendedTcpTable(buffer.data(), &dwSize, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);

} while( dwRetValue == ERROR_INSUFFICIENT_BUFFER);

if(dwRetValue == ERROR_SUCCESS)
{
// good case

// cast to access element values
PMIB_TCPTABLE_OWNER_PID ptTable = reinterpret_cast<PMIB_TCPTABLE_OWNER_PID>(buffer.data());

//cout << “Number of Entries1: ” << ptTable->dwNumEntries << endl << endl;
// caution: array starts with index 0, count starts by 1
for(DWORD i = 0; i < ptTable->dwNumEntries; i++)
{
tNetworkProcessInfo *processInfo = new tNetworkProcessInfo;

processInfo->pid = ptTable->table[i].dwOwningPid;
processInfo->processName=GetNameByPID(ptTable->table[i].dwOwningPid);

processInfo->state = ptTable->table[i].dwState;
sprintf_s(processInfo->localIP,”%lu.%lu.%lu.%lu”, (ptTable->table[i].dwLocalAddr & 0xFF), ((ptTable->table[i].dwLocalAddr >> 8) & 0xFF),
((ptTable->table[i].dwLocalAddr >> 16) & 0xFF), ((ptTable->table[i].dwLocalAddr >> 24) & 0xFF));

processInfo->localPort = (unsigned short)ptTable->table[i].dwLocalPort;
sprintf_s(processInfo->remoteIP,”%lu.%lu.%lu.%lu”, (ptTable->table[i].dwRemoteAddr & 0xFF), ((ptTable->table[i].dwRemoteAddr >> 8) & 0xFF),
((ptTable->table[i].dwRemoteAddr >> 16) & 0xFF), ((ptTable->table[i].dwRemoteAddr >> 24) & 0xFF));

processInfo->remotePort = (unsigned short)ptTable->table[i].dwRemotePort;

objNetworkProcessInfo.push_back(processInfo);
}

} else
{
// bad case, handle errorcodes
}

}

char * GetNameByPID(DWORD processPid) {
char *processName = NULL;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if(hSnapshot) {
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if(Process32First(hSnapshot,&pe32)) {
do {
if(processPid == pe32.th32ProcessID){
processName = _strdup(pe32.szExeFile);
break;
}
} while(Process32Next(hSnapshot,&pe32));
}
CloseHandle(hSnapshot);
}

return processName;
}