Search

'sample'에 해당되는 글 15건

  1. 2016.09.06 MFC Alert MessageBox2
  2. 2016.09.05 CPP aes128 str mode Encryption Decryption Using openssl library
  3. 2016.08.25 CDateTimeCtrl 사용법
  4. 2016.03.07 Winpcap Test 04
  5. 2016.03.07 Winpcap Test 03

MFC Alert MessageBox2

Programming/MFC 2016. 9. 6. 10:47 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

      int MessageBox(
   LPCTSTR lpszText,
   LPCTSTR lpszCaption = NULL,
   UINT nType = MB_OK 
);

lpszText

가리키는 있는 CString 개체 또는 표시 되는 메시지에 포함 된 null로 끝나는 문자열입니다.

lpszCaption

가리키는 있는 CString 개체 또는 null로 끝나는 문자열에 대 한 캡션을 메시지 상자를 사용할 수 있습니다. 경우 lpszCaption  NULL, 기본 캡션을 "오류"를 사용 합니다.

nType

콘텐츠 및 메시지 상자의 동작을 지정합니다.


전역 함수 사용 AfxMessageBox 응용 프로그램에서 메시지 상자를 구현 하려면이 멤버 함수를 대신 합니다.

다음은 메시지 상자에 사용할 수 있는 다양 한 시스템 아이콘입니다.

중지(x) 아이콘

MB_ICONHANDMB_ICONSTOP, 및 MB_ICONERROR

도움말(?) 아이콘

MB_ICONQUESTION

중요(!) 아이콘

MB_ICONEXCLAMATION 및 MB_ICONWARNING

정보(i) 아이콘

MB_ICONASTERISK 및 MB_ICONINFORMATION









void CMainFrame::OnDisplayErrorMessage()
{
   // This displays a message box with the title "Error"
   // and the message "Help, Something went wrong."
   // The error icon is displayed in the message box, along with
   // an OK button.
   MessageBox(_T("Help, Something went wrong."), _T("Error"), 
      MB_ICONERROR | MB_OK);
}




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

MFC Dialog Modal  (0) 2016.09.22
MFC Modal and Modeless Dialog Boxes  (0) 2016.09.06
MFC Alert MessageBox  (0) 2016.09.06
MFC Drag And Drop FileName 만 추출  (0) 2016.08.30
MFC File Icon Drag and Drop  (0) 2016.08.30
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

CPP aes128 cbc mode Encryption Decryption



AES


Encryption Block  : 

128 비트

192 비트 

256 비트


Mode :    

1. ECB ( Electric Code Book )

http://jo.centis1504.net/wp-content/uploads/2010/11/Encryption-ECB_MODE.swf




2. CBC ( Cipher Block Chaining )

http://jo.centis1504.net/wp-content/uploads/2010/11/Encryption-CBC_MODE.swf





3. OFB ( Output Feed Back )

http://jo.centis1504.net/wp-content/uploads/2010/11/Encryption-OFB_MODE.swf



4. CFB ( Cipher Feed Back )



5. CTR ( CounTeR )



모드별 설명은


관련 자료 참고 : http://www.parkjonghyuk.net/lecture/modernCrypto/lecturenote/chap04.pdf




구현에서는 CTR 모드로 구현하였다.






개발 환경 : Windows 7 64bit, VS 2013



최신버전으로 직접 빌드하시려면 아래의 링크를 참조하시기 바랍니다.


귀찮으신 분은 빌드된 버전을 사용합시다.


OpenSSL 빌드 : http://yokkohama.tistory.com/entry/OpenSSL-%EB%B9%8C%EB%93%9C%ED%95%98%EA%B8%B0-Visual-Studio-2010-%EB%98%90%EB%8A%94-libeay32dll-ssleay32dll-%EB%8B%A4%EC%9A%B4%EB%A1%9C%EB%93%9C



"openssl-1.0.1f_vc_no-idea no-mdc2 no-rc5_build.zip" 는 no-idea no-mdc2 no-rc5  로 빌드된, 특허문제가 해결 된 바이너리입니다.


openssl-1.0.1f_vc_no-idea no-mdc2 no-rc5_build.zip



압축 해제 후 파일을 프로젝트 폴더로 이동



프로젝트속성 > VC++ 디렉터리 > 디렉터리 설정 (포함 디렉터리, 라이브러리 디렉터리)






별도의 클래스를 만들어 사용 하였습니다.







#pragma once

#include 
#include 
#include 
#include 


struct ctr_state {
	unsigned char ivec[AES_BLOCK_SIZE];
	unsigned int num;
	unsigned char ecount[AES_BLOCK_SIZE];
};



class CAESCTR
{
public:
	AES_KEY key;
	int BYTES_SIZE = 1024;
	int KEY_SIZE = 128;
	unsigned char ckey[32];
	unsigned char iv[8];
	int init_ctr(struct ctr_state *state, const unsigned char iv[8]);
	void encrypt(unsigned char *indata, unsigned char *outdata, int bytes_read);
	void encrypt(CString& indata, CString& outdata, int bytes_read);
	CAESCTR();
	CAESCTR::CAESCTR(unsigned char* iv, unsigned char* ckey);
	~CAESCTR();
};







#include "stdafx.h"
#include "AESCTR.h"

int CAESCTR::init_ctr(struct ctr_state *state, const unsigned char iv[8]){
	state->num = 0;
	memset(state->ecount, 0, AES_BLOCK_SIZE);
	memset(state->ivec + 8, 0, 8);
	memcpy(state->ivec, iv, 8);

	return 0;
}
// encrypt twice  == decrypt

void CAESCTR::encrypt(unsigned char *indata, unsigned char *outdata, int bytes_read){

	int i = 0;
	int mod_len = 0;

	AES_set_encrypt_key(ckey, KEY_SIZE, &key);

	if (bytes_read < BYTES_SIZE){
		struct ctr_state state;
		init_ctr(&state, iv);
		AES_ctr128_encrypt(indata, outdata, bytes_read, &key, state.ivec, state.ecount, &state.num);
		return;
	}
	// loop block size  = [ BYTES_SIZE ]
	for (i = BYTES_SIZE; i <= bytes_read; i += BYTES_SIZE){
		struct ctr_state state;
		init_ctr(&state, iv);
		AES_ctr128_encrypt(indata, outdata, BYTES_SIZE, &key, state.ivec, state.ecount, &state.num);
		indata += BYTES_SIZE;
		outdata += BYTES_SIZE;
	}

	mod_len = bytes_read % BYTES_SIZE;
	if (mod_len != 0){
		struct ctr_state state;
		init_ctr(&state, iv);
		AES_ctr128_encrypt(indata, outdata, mod_len, &key, state.ivec, state.ecount, &state.num);
	}
}

void CAESCTR::encrypt(CString& instr, CString& outstr, int bytes_read){

	int i = 0;
	int mod_len = 0;
	unsigned char *indata;
	unsigned char *outdata;

	indata = (unsigned char *)malloc(instr.GetLength() + 1);
	outdata = (unsigned char *)malloc(instr.GetLength() + 1);



	strncpy((char*)indata, (LPSTR)(LPCSTR)instr, instr.GetLength());
	indata[instr.GetLength()] = NULL;


	

	AES_set_encrypt_key(ckey, KEY_SIZE, &key);

	if (bytes_read < BYTES_SIZE){
		struct ctr_state state;
		init_ctr(&state, iv);
		AES_ctr128_encrypt(indata, outdata, bytes_read, &key, state.ivec, state.ecount, &state.num);

		outdata[instr.GetLength()] = NULL;
		outstr = outdata;
		return;
	}
	// loop block size  = [ BYTES_SIZE ]
	for (i = BYTES_SIZE; i <= bytes_read; i += BYTES_SIZE){
		struct ctr_state state;
		init_ctr(&state, iv);
		AES_ctr128_encrypt(indata, outdata, BYTES_SIZE, &key, state.ivec, state.ecount, &state.num);
		indata += BYTES_SIZE;
		outdata += BYTES_SIZE;
	}

	mod_len = bytes_read % BYTES_SIZE;
	if (mod_len != 0){
		struct ctr_state state;
		init_ctr(&state, iv);
		AES_ctr128_encrypt(indata, outdata, mod_len, &key, state.ivec, state.ecount, &state.num);
	}
	outdata[instr.GetLength()] = NULL;
	outstr = outdata;
}

CAESCTR::CAESCTR()
{
	unsigned char temp_iv[8] = { 0x66, 0x61, 0x63, 0x65, 0x73, 0x65, 0x61, 0x00 };
	memcpy(iv, temp_iv, 8);

	unsigned char temp_ckey[32] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
		0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
		0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34,
		0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56 }; // 32bytes = AES256, 16bytes = AES128
	memcpy(ckey, temp_ckey, 32);
}

CAESCTR::CAESCTR(unsigned char* iv, unsigned char* ckey)
{
	memcpy(this->iv, iv, 8);
	memcpy(this->ckey, ckey, 32);
}

CAESCTR::~CAESCTR()
{
}






그리고, 프로젝트 속성에서


구성 속성 > 문자 집합 > 설정 안 함


으로 하여서 사용하였습니다.



사용예시










void CPasswordEncoderDlg::OnEnChangeEdit1()
{
	// TODO:  RICHEDIT 컨트롤인 경우, 이 컨트롤은
	// CDialogEx::OnInitDialog() 함수를 재지정 
	//하고 마스크에 OR 연산하여 설정된 ENM_CHANGE 플래그를 지정하여 CRichEditCtrl().SetEventMask()를 호출하지 않으면
	// 이 알림 메시지를 보내지 않습니다.

	// TODO:  여기에 컨트롤 알림 처리기 코드를 추가합니다.
	CAESCTR m_AESCTR;

	CString editText;
	m_Edit1.GetWindowTextA(editText);
		
	int editTextLength = editText.GetLength();

	unsigned char* editTextCharSeq;
	editTextCharSeq = (unsigned char *)malloc(editTextLength+1);

	strncpy((char*)editTextCharSeq, (LPSTR)(LPCSTR)editText, editTextLength);
	editTextCharSeq[editTextLength] = NULL;

	unsigned char* outTextCharSeq;
	outTextCharSeq = (unsigned char *)malloc(editTextLength + 1);

	m_AESCTR.encrypt(editTextCharSeq, outTextCharSeq, editTextLength);
	outTextCharSeq[editTextLength] = NULL;
	
	editText = outTextCharSeq;
	m_Edit2.SetWindowTextA(editText);
	
	m_AESCTR.encrypt(editText, editText, editTextLength);

	m_Edit3.SetWindowTextA(editText);

	free(editTextCharSeq);
	free(outTextCharSeq);
}










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

openssl AES encrypt (AES_ctr128_encrypt)  (0) 2016.09.19
openssl AES Mode : ECB, CBC, CFB, OFB, CTR  (0) 2016.09.05
CDateTimeCtrl 사용법  (0) 2016.08.25
Apache License, Version 2.0  (0) 2016.08.22
Log4cxx ChainSaw Appender  (0) 2016.08.22

CDateTimeCtrl 사용법

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

CDateTimeCtrl 사용법



이름

설명

CDateTimeCtrl::CloseMonthCal

현재 날짜 및 시간 선택 컨트롤을 닫습니다.

CDateTimeCtrl::Create

날짜 및 시간 선택 컨트롤을 만들고이에 연결 된 CDateTimeCtrl 개체입니다.

CDateTimeCtrl::GetDateTimePickerInfo

현재 날짜 및 시간 선택 컨트롤에 대 한 정보를 검색합니다.

CDateTimeCtrl::GetIdealSize

현재 날짜나 시간을 표시 하는 데 필요한 시간 및 날짜 선택 컨트롤의 이상적인 크기를 반환 합니다.

CDateTimeCtrl::GetMonthCalColor

월 달력에서 날짜 및 시간 선택 컨트롤의 특정된 부분에 대 한 색을 검색합니다.

CDateTimeCtrl::GetMonthCalCtrl

검색은 CMonthCalCtrl 개체의 날짜 및 시간 선택 컨트롤에 연결 합니다.

CDateTimeCtrl::GetMonthCalFont

현재 날짜 및 시간 선택 컨트롤의 자식 컨트롤에서 사용 되는 글꼴을 검색 합니다.

CDateTimeCtrl::GetMonthCalStyle

현재 날짜 및 시간 선택 컨트롤의 스타일을 가져옵니다.

CDateTimeCtrl::GetRange

현재 최소 및 최대 허용 시스템 시간 날짜 및 시간 선택 컨트롤을 검색 합니다.

CDateTimeCtrl::GetTime

날짜 및 시간 선택 컨트롤에서 현재 선택한 시간을 검색 하 고 지정 된 배치 SYSTEMTIME 구조.

CDateTimeCtrl::SetFormat

지정 된 형식 문자열에 따라 날짜 및 시간 선택 컨트롤의 표시를 설정합니다.

CDateTimeCtrl::SetMonthCalColor

월 달력에서 날짜 및 시간 선택 컨트롤의 특정된 부분에 대 한 색을 설정합니다.

CDateTimeCtrl::SetMonthCalFont

날짜 및 시간 선택 컨트롤의 자식 컨트롤을 사용 하는 글꼴을 설정 합니다.

CDateTimeCtrl::SetMonthCalStyle

현재 날짜 및 시간 선택 컨트롤의 스타일을 설정합니다.

CDateTimeCtrl::SetRange

날짜 및 시간 선택 컨트롤에 대 한 최소 및 최대 허용 된 시스템 시간을 설정합니다.

CDateTimeCtrl::SetTime

날짜 및 시간 선택 컨트롤에는 시간을 설정합니다.




// set with a CTime
CTime timeTime(1998, 4, 3, 0, 0, 0);
VERIFY(m_DateTimeCtrl.SetTime(&timeTime));

// set with a COleDateTime object
COleDateTime oletimeTime(1998, 4, 3, 0, 0, 0);
VERIFY(m_DateTimeCtrl.SetTime(oletimeTime));

// set using the SYSTEMTIME
SYSTEMTIME sysTime;
memset(&sysTime, 0, sizeof(sysTime));
sysTime.wYear = 1998;
sysTime.wMonth = 4;
sysTime.wDay = 3;
VERIFY(m_DateTimeCtrl.SetTime(&sysTime));
void CDateTimeDlg::OnBnClickedTimebutton()
{
   // get as a CTime
   CTime timeTime;
   DWORD dwResult = m_DateTimeCtrl.GetTime(timeTime);
   if (dwResult == GDT_VALID)
   {
      // the user checked the box and specified data
      CString str;

      // is it a time-only control, or a date-only control?
      if ((m_DateTimeCtrl.GetStyle() & DTS_TIMEFORMAT) == DTS_TIMEFORMAT)
         str = timeTime.Format(_T("%X"));
      else
         str = timeTime.Format(_T("%x"));
      AfxMessageBox(str);
   }
   else
   {
      // the user unmarked the "none" box
      AfxMessageBox(_T("Time not set!"));
   }

   // Calling as SYSTIME is much the same, but calling for a COleDateTime
   // has us test the state of the COleDateTime object for validity to 
   // see if the user did or didn't check the "none" box.
}











Winpcap Test 04

Programming/C,CPP,CS 2016. 3. 7. 09:49 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

응용


02,03 Test 를 합친다.


03 에서의 목록으로는 어떤 디바이스가 내가 캡쳐할 디바이스인지를 구분하기가 어렵다.


02에서의 상세정보를 활용하여 정리한다.



 

/*

* Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)

* Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)

* All rights reserved.

*

* Redistribution and use in source and binary forms, with or without

* modification, are permitted provided that the following conditions

* are met:

*

* 1. Redistributions of source code must retain the above copyright

* notice, this list of conditions and the following disclaimer.

* 2. Redistributions in binary form must reproduce the above copyright

* notice, this list of conditions and the following disclaimer in the

* documentation and/or other materials provided with the distribution.

* 3. Neither the name of the Politecnico di Torino, CACE Technologies 

* nor the names of its contributors may be used to endorse or promote 

* products derived from this software without specific prior written 

* permission.

*

* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS

* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT

* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR

* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT

* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,

* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT

* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,

* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY

* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT

* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE

* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*

*/


#include <stdio.h>


#include "pcap.h"


#ifndef WIN32

#include <sys/socket.h>

#include <netinet/in.h>

#else

#include <winsock.h>

#endif



// Function prototypes

void ifprint(pcap_if_t *d);

char *iptos(u_long in);

char* ip6tos(struct sockaddr *sockaddr, char *address, int addrlen);

void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);



int main()

{

pcap_if_t *alldevs;

pcap_if_t *d;

char errbuf[PCAP_ERRBUF_SIZE+1];

char source[PCAP_ERRBUF_SIZE+1] = {'0'};

int inum;

int i = 0;

pcap_t *adhandle;



if (pcap_findalldevs_ex(source, NULL, &alldevs, errbuf) == -1)

{

fprintf(stderr,"Error in pcap_findalldevs: %s\n",errbuf);

exit(1);

}


/* Scan the list printing every entry */

for(d=alldevs;d;d=d->next)

{

ifprint(d);

i++;

}


printf("Enter the interface number (1-%d):",i);

scanf_s("%d", &inum);



if(inum < 1 || inum > i)

{

printf("\nInterface number out of range.\n");

/* Free the device list */

pcap_freealldevs(alldevs);

return -1;

}


/* Jump to the selected adapter */

for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);





/* Open the device */

if ( (adhandle= pcap_open(d->name,          // name of the device

65536,            // portion of the packet to capture

// 65536 guarantees that the whole packet will be captured on all the link layers

PCAP_OPENFLAG_PROMISCUOUS,    // promiscuous mode

1000,             // read timeout

NULL,             // authentication on the remote machine

errbuf            // error buffer

) ) == NULL)

{

fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);

/* Free the device list */

pcap_freealldevs(alldevs);

return -1;

}


printf("\nlistening on %s...\n", d->description);


/* At this point, we don't need any more the device list. Free it */

pcap_freealldevs(alldevs);


/* start the capture */

pcap_loop(adhandle, 0, packet_handler, NULL);



return 1;

}




/* Print all the available information on the given interface */

void ifprint(pcap_if_t *d)

{

pcap_addr_t *a;

char ip6str[128];


/* Name */

printf("\tName: %s\n",d->name);


/* Description */

if (d->description)

printf("\tDescription: %s\n",d->description);


/* Loopback Address*/

printf("\tLoopback: %s\n",(d->flags & PCAP_IF_LOOPBACK)?"yes":"no");


/* IP addresses */

for(a=d->addresses;a;a=a->next) {

if(a->addr->sa_family != AF_INET)

continue;


printf("\tAddress Family Name: AF_INET\n");

if (a->addr)

printf("\tAddress: %s\n",iptos(((struct sockaddr_in *)a->addr)->sin_addr.s_addr));

if (a->netmask)

printf("\tNetmask: %s\n",iptos(((struct sockaddr_in *)a->netmask)->sin_addr.s_addr));

if (a->broadaddr)

printf("\tBroadcast Address: %s\n",iptos(((struct sockaddr_in *)a->broadaddr)->sin_addr.s_addr));

if (a->dstaddr)

printf("\tDestination Address: %s\n",iptos(((struct sockaddr_in *)a->dstaddr)->sin_addr.s_addr));

}

printf("\n");

}




/* From tcptraceroute, convert a numeric IP address to a string */

#define IPTOSBUFFERS    12

char *iptos(u_long in)

{

static char output[IPTOSBUFFERS][3*4+3+1];

static short which;

u_char *p;


p = (u_char *)&in;

which = (which + 1 == IPTOSBUFFERS ? 0 : which + 1);

_snprintf_s(output[which], sizeof(output[which]), sizeof(output[which]),"%d.%d.%d.%d", p[0], p[1], p[2], p[3]);

return output[which];

}


char* ip6tos(struct sockaddr *sockaddr, char *address, int addrlen)

{

socklen_t sockaddrlen;


#ifdef WIN32

sockaddrlen = sizeof(struct sockaddr_in6);

#else

sockaddrlen = sizeof(struct sockaddr_storage);

#endif



if(getnameinfo(sockaddr, 

sockaddrlen, 

address, 

addrlen, 

NULL, 

0, 

NI_NUMERICHOST) != 0) address = NULL;


return address;

}


/* Callback function invoked by libpcap for every incoming packet */

void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)

{

struct tm ltime;

char timestr[16];

time_t local_tv_sec;


/*

* unused variables

*/

(VOID)(param);

(VOID)(pkt_data);


/* convert the timestamp to readable format */

local_tv_sec = header->ts.tv_sec;

localtime_s(&ltime, &local_tv_sec);

strftime( timestr, sizeof timestr, "%H:%M:%S", &ltime);


printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);


}


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

Winpcap Test 06  (0) 2016.03.07
Winpcap Test 05  (0) 2016.03.07
Winpcap Test 03  (0) 2016.03.07
Winpcap Test 02  (0) 2016.03.07
Winpcap Test 01  (0) 2016.03.07

Winpcap Test 03

Programming/C,CPP,CS 2016. 3. 7. 09:11 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Opening an adapter and capturing the packets


#include "pcap.h"

/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);

int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
    
    /* Retrieve the device list on the local machine */
    if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
    {
        fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
        exit(1);
    }
    
    /* Print the list */
    for(d=alldevs; d; d=d->next)
    {
        printf("%d. %s", ++i, d->name);
        if (d->description)
            printf(" (%s)\n", d->description);
        else
            printf(" (No description available)\n");
    }
    
    if(i==0)
    {
        printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
        return -1;
    }
    
    printf("Enter the interface number (1-%d):",i);
    scanf_s("%d", &inum);
    
    if(inum < 1 || inum > i)
    {
        printf("\nInterface number out of range.\n");
        /* Free the device list */
        pcap_freealldevs(alldevs);
        return -1;
    }
    
    /* Jump to the selected adapter */
    for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
    
    /* Open the device */
    if ( (adhandle= pcap_open(d->name,          // name of the device
                              65536,            // portion of the packet to capture
                                                // 65536 guarantees that the whole packet will be captured on all the link layers
                              PCAP_OPENFLAG_PROMISCUOUS,    // promiscuous mode
                              1000,             // read timeout
                              NULL,             // authentication on the remote machine
                              errbuf            // error buffer
                              ) ) == NULL)
    {
        fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
        /* Free the device list */
        pcap_freealldevs(alldevs);
        return -1;
    }
    
    printf("\nlistening on %s...\n", d->description);
    
    /* At this point, we don't need any more the device list. Free it */
    pcap_freealldevs(alldevs);
    
    /* start the capture */
    pcap_loop(adhandle, 0, packet_handler, NULL);
    
    return 0;
}


/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
    struct tm ltime;
    char timestr[16];
    time_t local_tv_sec;

    /*
     * unused variables
     */
    (VOID)(param);
    (VOID)(pkt_data);

    /* convert the timestamp to readable format */
    local_tv_sec = header->ts.tv_sec;
    localtime_s(&ltime, &local_tv_sec);
    strftime( timestr, sizeof timestr, "%H:%M:%S", &ltime);
    
    printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
    
}




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

Winpcap Test 05  (0) 2016.03.07
Winpcap Test 04  (0) 2016.03.07
Winpcap Test 02  (0) 2016.03.07
Winpcap Test 01  (0) 2016.03.07
CPP 2015-01-15 수업내용 정리  (0) 2015.01.15