336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

[NTP] CNtpTime, sntp.h, sntp.cpp 의 문제점 정리

 

NTP 프로토콜을 이용하여 클라이언트 시간 동기화시

 

sntp.h, sntp.cpp 로 만들어진

 

CNtpTime 클래스를 많이 사용하는것 같다.

 

ex)

 

https://github.com/hsluoyz/rmtsvc/blob/master/net4cpp21/protocol/sntpclnt.cpp

 

hsluoyz/rmtsvc

A web-based remote desktop & control service for Windows. - hsluoyz/rmtsvc

github.com

http://read.pudn.com/downloads142/sourcecode/hack/trojan/616424/sntpclient%202008-08-03/NtpTime.c__.htm

 

sntpclient.rar NtpTime.c

www.pudn.com > sntpclient.rar > NtpTime.c, change:2008-08-25,size:4890b #include "NtpTime.h" #include "datatype.h" #include #include #define FALSE 0 SYSTEMTIME st; CNtpTimePacket host2network(CNtpTimePacket ntp) //transform the host byte order to network b

read.pudn.com

https://github.com/domz1/integrity/blob/master/Source/Virtuos_v17/Build/Program/_Network/Misc/Src/Sntp.cpp

 

domz1/integrity

Contribute to domz1/integrity development by creating an account on GitHub.

github.com

 

위 코드들 모두 누군가 만든 CNtpTime 을 그대로 사용하고있는데...

 

그런데 이 클래스에 문제점이 있다.

 

 

 

CNtpTime::operator SYSTEMTIME() 

 

CNtpTime 을 SystemTime 으로 형변환 해주는 오퍼레이터 함수인데

 

 

  st.wMilliseconds = NtpFractionToMs(Fraction());

 

이 부분에 문제가 있다.

 

Fraction 을 Milliseconds 로 변경한 결과가 1000 이 되는 경우가 발생한다.

 

NtpTime 실제 값을 저장 할 시에

 

FileTime 을 사용하는데

 

FileTime 은

 

Second 와 NanoSecond 를 구분하여 16진수 기준 앞 8자리 뒤 8자리로 표현한다.

 

NanoSecond 의 값이 0x100000000 이 1Second 인데

 

NanoSecond 의 표현부는 0xFFFFFFF 이므로 1Second 도 0xFFFFFFF 로 표기된다.

 

 

 

CNtpTime::operator SYSTEMTIME() const
{
// Currently this function only operates correctly in
// the 1900- 2036 primary epoch defined by NTP
SYSTEMTIME st;
DWORD s = Seconds();
st.wSecond = (WORD)( s % 60 );
s /= 60;
st.wMinute = (WORD)( s % 60 );
s /= 60;
st.wHour = (WORD)( s % 24 );
s /= 24;
long JD = s + JAN_1ST_1900;
st.wDayOfWeek = (WORD)( ( JD + 1 ) % 7 );
GetGregorianDate( JD, st.wYear, st.wMonth, st.wDay );
st.wMilliseconds = NtpFractionToMs( Fraction() );
 
return st;
}

 

위 구조 상

 

NtpFractionToMs( Fraction() ) 의 결과값이 1000 이어도

 

Second 로의 올림이 발생하지 않아서

 

Milliseconds 가 1000 인 채로 다음 연산으로 넘어가게 된다.

 

 

Milliseconds 가 1000 인 상태에서

 

SystemTime 을 FileTime 으로 바꾸는 SystemTimeToFileTime 함수를 실행하게 되면

 

비정상값이 리턴된다.

 

 

 

 

 

Audio Wave Form Renderer

Programming/C# 2018. 10. 24. 15:13 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Audio Wave Form Renderer




Test Harness App


Test Harness UI


Example Waveforms


Basic solid colour waveform Basic solid color

Gradient vertical bars (old SoundCloud style) Gradient vertical bars

Blocks (SoundCloud style) Blocks

Orange Blocks

Transparent Backgrounds Transparent Background

Transparent Background

You can check out all the source code on GitHub





https://markheath.net/post/naudio-png-waveform-rendering

중복 실행 방지 코드 (Mutex)

Programming/C,CPP,CS 2018. 4. 18. 15:08 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

중복 실행 방지 코드 (Mutex)


CreateMutex function


Creates or opens a named or unnamed mutex object.

To specify an access mask for the object, use the CreateMutexEx function.

Syntax

HANDLE WINAPI CreateMutex(
  _In_opt_ LPSECURITY_ATTRIBUTES lpMutexAttributes,
  _In_     BOOL                  bInitialOwner,
  _In_opt_ LPCTSTR               lpName
);

Parameters

lpMutexAttributes [in, optional]

A pointer to a SECURITY_ATTRIBUTES structure. If this parameter is NULL, the handle cannot be inherited by child processes.

The lpSecurityDescriptor member of the structure specifies a security descriptor for the new mutex. If lpMutexAttributes is NULL, the mutex gets a default security descriptor. The ACLs in the default security descriptor for a mutex come from the primary or impersonation token of the creator. For more information, see Synchronization Object Security and Access Rights.

bInitialOwner [in]

If this value is TRUE and the caller created the mutex, the calling thread obtains initial ownership of the mutex object. Otherwise, the calling thread does not obtain ownership of the mutex. To determine if the caller created the mutex, see the Return Values section.

lpName [in, optional]

The name of the mutex object. The name is limited to MAX_PATH characters. Name comparison is case sensitive.

If lpName matches the name of an existing named mutex object, this function requests the MUTEX_ALL_ACCESSaccess right. In this case, the bInitialOwner parameter is ignored because it has already been set by the creating process. If the lpMutexAttributes parameter is not NULL, it determines whether the handle can be inherited, but its security-descriptor member is ignored.

If lpName is NULL, the mutex object is created without a name.

If lpName matches the name of an existing event, semaphore, waitable timer, job, or file-mapping object, the function fails and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same namespace.

The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session namespace. The remainder of the name can contain any character except the backslash character (\). For more information, see Kernel Object Namespaces. Fast user switching is implemented using Terminal Services sessions. Kernel object names must follow the guidelines outlined for Terminal Services so that applications can support multiple users.

The object can be created in a private namespace. For more information, see Object Namespaces.




#include <windows.h>
#include <stdio.h>

#define THREADCOUNT 2

HANDLE ghMutex; 

DWORD WINAPI WriteToDatabase( LPVOID );

int main( void )
{
    HANDLE aThread[THREADCOUNT];
    DWORD ThreadID;
    int i;

    // Create a mutex with no initial owner

    ghMutex = CreateMutex( 
        NULL,              // default security attributes
        FALSE,             // initially not owned
        NULL);             // unnamed mutex

    if (ghMutex == NULL) 
    {
        printf("CreateMutex error: %d\n", GetLastError());
        return 1;
    }

    // Create worker threads

    for( i=0; i < THREADCOUNT; i++ )
    {
        aThread[i] = CreateThread( 
                     NULL,       // default security attributes
                     0,          // default stack size
                     (LPTHREAD_START_ROUTINE) WriteToDatabase, 
                     NULL,       // no thread function arguments
                     0,          // default creation flags
                     &ThreadID); // receive thread identifier

        if( aThread[i] == NULL )
        {
            printf("CreateThread error: %d\n", GetLastError());
            return 1;
        }
    }

    // Wait for all threads to terminate

    WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);

    // Close thread and mutex handles

    for( i=0; i < THREADCOUNT; i++ )
        CloseHandle(aThread[i]);

    CloseHandle(ghMutex);

    return 0;
}

DWORD WINAPI WriteToDatabase( LPVOID lpParam )
{ 
    // lpParam not used in this example
    UNREFERENCED_PARAMETER(lpParam);

    DWORD dwCount=0, dwWaitResult; 

    // Request ownership of mutex.

    while( dwCount < 20 )
    { 
        dwWaitResult = WaitForSingleObject( 
            ghMutex,    // handle to mutex
            INFINITE);  // no time-out interval
 
        switch (dwWaitResult) 
        {
            // The thread got ownership of the mutex
            case WAIT_OBJECT_0: 
                __try { 
                    // TODO: Write to the database
                    printf("Thread %d writing to database...\n", 
                            GetCurrentThreadId());
                    dwCount++;
                } 

                __finally { 
                    // Release ownership of the mutex object
                    if (! ReleaseMutex(ghMutex)) 
                    { 
                        // Handle error.
                    } 
                } 
                break; 

            // The thread got ownership of an abandoned mutex
            // The database is in an indeterminate state
            case WAIT_ABANDONED: 
                return FALSE; 
        }
    }
    return TRUE; 
}



'Programming > C,CPP,CS' 카테고리의 다른 글

ActiveX 웹배포  (0) 2019.12.10
ffmpeg sample  (0) 2018.06.20
WAVE form wFormatTag IDs  (0) 2018.04.04
CString Tokenize  (0) 2017.10.19
[CPP] Windows Service 간단하게 만들기  (0) 2017.10.17

JNA Error

Programming/JAVA,JSP 2018. 2. 27. 15:48 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

JNA Error













int hr = m_pObjectKey.CreateInstance(__uuidof(KeyObject));


해당 구문에서


CreateInstance 의 리턴 값이



%x : 80040154


%d : -2147221164


형태로 계속 리턴되는 경우








80040154 오류
















System.Runtime.InteropServices.COMExcetption : 80040154 오류로 인해 CLSID가 {100202C1-E260-11CF-AE68-00AA004A34D5}인 구성 요소의 COM 클래스 팩터리를 검색하지 못했습니다.


https://social.msdn.microsoft.com/Forums/vstudio/ko-KR/03d5a6bd-e256-492a-a72b-f011b971834e/80040154-?forum=visualcsharpko
















쉽게 말하면 해당 라이브러리의 DLL 파일의 경로를 찾을수 없어서


객체를 만들 수 없다는 이야기이다.



















1) regasm, regsrv 를 이용하여 재등록을 시도해 보고,







그래도 안된다면









2) regasm 의 경우 /codebase 옵션을 사용 해 보라






























C# 에서 C++ DLL 불러서 쓰기 #4

Programming/C# 2018. 2. 14. 12:30 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

C# 에서 C++ DLL 불러서 쓰기 #4



4. 멤버 함수 가져오기





C++


#ifdef BOX_EXPORTS

#define BOX_API __declspec(dllexport)

#else

#define BOX_API __declspec(dllimport)

#endif






Class BOX_API Box{

public:

Box();

int setInt(int a);

void setString(char* str);

}






int setInt(int a);

void setString(char* str);




이 멤버 함수들을 가져와서 사용하고 싶다.



참고 : http://tansanc.tistory.com/526?category=772232 [TanSanC]





아래와 같이 사용하고 싶지만


불가능하다



namespace BoxConsoleApplication

{

    class Program

    {


        [DllImport("Box.dll", CallingConvention = CallingConvention.Cdecl)]

        static public extern IntPtr CreateCBox();

        

        

        [DllImport("Box.dll", CallingConvention = CallingConvention.Cdecl)]

        static public extern void DisposeCBox(IntPtr pTestClassObject);


        unsafe static void Main(string[] args)

        {


            IntPtr pCBoxClass = CreateCBox(); ;



            pCBoxClass.setInt(3);

            pCBoxClass.setString("HelloWorld");




            DisposeCBox(pCBoxClass );            




            pCBoxClass = IntPtr.Zero; 


        }

    }

}





            pCBoxClass.setInt(3);

            pCBoxClass.setString("HelloWorld");




클래스 내부 멤버 변수라 바로 가져올 수는 없다.






사용 할 수 있는 방법은


클래스 생성시와 같이


extern 으로 접근가능 하도록 만들어 주어야 한다.











기본 형태





C++






.h


extern "C" BOX_API int setInt(CBox* pObject, int a);






.cpp


extern "C" BOX_API int setInt(CBox* pObject, int a)

{

if (pObject != NULL)

{

pObject->setInt(a);

}

return -1;

}





이렇게 C++ DLL 내부에서 


클래스 객체에 접근하여


객체의 멤버 함수를 호출하여 준다.











void setString(char* str);



는 다음 글에서....






336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

C# 에서 C++ DLL 불러서 쓰기


도움되는 링크들





http://freeprog.tistory.com/220




https://docs.microsoft.com/ko-kr/dotnet/csharp/language-reference/keywords/unsafe



http://heroeskdw.tistory.com/entry/C-MFC-DLL%EC%9D%84-C%EC%97%90%EC%84%9C-%EB%A1%9C%EB%94%A9%ED%95%98%EA%B8%B0


https://www.codeproject.com/Articles/18032/How-to-Marshal-a-C-Class




http://www.sysnet.pe.kr/2/0/11132







http://www.sysnet.pe.kr/2/0/11111







https://msdn.microsoft.com/ko-kr/library/62688esh.aspx












https://social.msdn.microsoft.com/Forums/en-US/b85fc9dd-acc5-42dc-a28e-b70953bf1170/unhandled-exception-systemruntimeinteropservicessehexception-additional-information-external?forum=vcgeneral

















https://msdn.microsoft.com/ko-kr/library/system.io.filestream.read(v=vs.110).aspx







http://storycompiler.tistory.com/214






























C# 에서 C++ DLL 불러서 쓰기 #2

Programming/C# 2018. 2. 13. 15:55 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

C# 에서 C++ DLL 불러서 쓰기 #2



2. DLL 참조하기




C++ DLL 을 C# 에서 사용하려면


일단 참조를 하여야 한다.




참조를 하는 방법은




Visual Studio 2013 버전에서는






[솔루션 탐색기] -> [솔루션] 하위 -> [프로젝트] 하위 -> [참조] -> 우클릭 -> [참조 추가] -> 우측 하단 [찾아보기(B)...] -> 원하는 DLL 찾아서 선택



선택을 하면 [참조] 하단에 참조된 DLL 이 보이게 된다.










여기서.......



이 글은


참조된 DLL 을 더블클릭하여 [개체 브라우저]로 보았을때도


하위 멤버들이 보이지 않는


C++ DLL 일 경우 해결하는 방법들을


순서...에 상관없이


메모해 두려고 한다.









336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

[CPP] Windows Service 간단하게 만들기

















Service.cpp

Service.h




Service 클래스 추가




stdafx.h 에 필요한 헤더파일 추가



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





main.cpp 에 필요한 내용 추가



// ConsoleApplication5.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.

//

 

#include "stdafx.h"

#include "Service.h"

#include "ConsoleApplication5.h"

 

#ifdef _DEBUG

#define new DEBUG_NEW

#endif

 

 

UINT MTServerThread(LPVOID pParam);

class CUpdateService : public CService{

public:

      CWinThread *_thread;

      void main(void){

            CService::Begin(_T("ConsoleApplication5"));

 

            // TODO : 서비스에서 실행 할 작업을 아래에 작성합니다.

 

            CService::End();

      }

protected:

      void OnStarted(){

            _thread = AfxBeginThread(MTServerThread, 0);

      }

      void OnStopped(){

            DWORD dwExitCode;

            GetExitCodeThread(_thread->m_hThread, &dwExitCode);

            WSACleanup();

      }

};

UINT MTServerThread(LPVOID pParam){

      return 0;

 

}

 

 

// 유일한 응용 프로그램 개체입니다.

 

CWinApp theApp;

 

using namespace std;

 

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])

{

      int nRetCode = 0;

 

      HMODULE hModule = ::GetModuleHandle(NULL);

 

      if (hModule != NULL)

      {

            // MFC를 초기화합니다. 초기화하지 못한 경우 오류를 인쇄합니다.

            if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))

            {

                  // TODO: 오류 코드를 필요에 따라 수정합니다.

                  _tprintf(_T("심각한 오류: MFC를 초기화하지 못했습니다.\n"));

                  nRetCode = 1;

            }

            else

            {

                  // TODO: 응용 프로그램의 동작은 여기에서 코딩합니다.

                  CUpdateService upServ;

                  if (argc == 2){

                        if (_tcscmp(argv[1], _T("-i")) == 0){

                             upServ.Install(_T("ConsoleApplication5"));

                        }

                        else if (_tcscmp(argv[1], _T("-u")) == 0){

                             upServ.Uninstall(_T("ConsoleApplication5"));

                        }

                        return true;

                  }

                  upServ.main();

            }

      }

      else

      {

            // TODO: 오류 코드를 필요에 따라 수정합니다.

            _tprintf(_T("심각한 오류: GetModuleHandle 실패\n"));

            nRetCode = 1;

      }

 

      return nRetCode;

}

 





'Programming > C,CPP,CS' 카테고리의 다른 글

WAVE form wFormatTag IDs  (0) 2018.04.04
CString Tokenize  (0) 2017.10.19
WaitForMultipleObjects  (0) 2017.04.19
How do I add my domain name to my computers host file?  (0) 2017.04.06
[VS2013] 힙이 손상되었습니다.  (0) 2017.04.05

[jsoncpp] getList Names

Programming/C,CPP,CS 2017. 2. 6. 17:07 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


"List" : {

         "value1" : "10.1.1.1",

         "value2" : "0.0.0.0"

      }




위의 경우에서 "10.1.1.1" , "0,0,0,0" 을 얻을 때에는,




for (auto itr : configuration_value.get("List", ""))

{

char* buf = (char*)malloc(BUFSIZE);

try{

sprintf_s(buf, BUFSIZE, "%s", itr.asString().c_str());

}

   }




위의 경우에서 "value1" , "value2" 을 얻을 때에는,



for ( auto const& id : configuration_value.get("List", "").getMemberNames() ) {

std::cout << id << std::endl;

}

Hiredis SMEMBERS 활용

Programming/Redis 2017. 1. 24. 13:34 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Hiredis SMEMBERS 활용








	redisReply *reply;
	redisAppendCommand(context, "SMEMBERS myset");
	redisGetReply(context, (void**)&reply);
	for (int i = 0; i < reply->elements; i++)
	{
		// reply->element[i]->str; // myset
	}

	freeReplyObject(reply);












참고 : https://redis.io/commands/smembers

참고 : https://github.com/redis/hiredis/blob/master/examples/example.c



'Programming > Redis' 카테고리의 다른 글

Redis Client Connect Test  (0) 2016.10.26
Hiredis Subscribe/Publish with CWinThread  (0) 2016.10.05
How to use Pub/sub with hiredis in C++?  (0) 2016.09.29
hiredis fatal error C1853:  (0) 2016.09.29
hiredis MFC import Visual Studio 2013  (0) 2016.09.28