⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 capturepacketdlg.cpp

📁 This article describes a sniffer for Windows. WinSniff is an application for capturing packets on th
💻 CPP
📖 第 1 页 / 共 2 页
字号:
//////////////////////////////////////////////////////////////////////////////
//
//   WinSniff 1.1
//   The sniffing tool for windows.
//
//   Author  : Nagareshwar Y Talekar.
//	 Contact : nsry2002@yahoo.co.in
//	 Date    : 15-6-2004.
//
//   Name :  CapturePacketDlg.cpp
//   Description :  Displays main dialog of the application.
//
//////////////////////////////////////////////////////////////////////////////


#include "stdafx.h"
#include "CapturePacket.h"
#include "Protocol.h"
#include "CapturePacketDlg.h"
#include "SelectDlg.h"


#include <pcap.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CCapturePacketDlg dialog

CCapturePacketDlg::CCapturePacketDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CCapturePacketDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CCapturePacketDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CCapturePacketDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CCapturePacketDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CCapturePacketDlg, CDialog)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_NOTIFY(NM_CLICK,IDC_LIST1,OnRowSelect)
	ON_NOTIFY(NM_DBLCLK,IDC_TREE1,OnTreeSelect)
	
	//Hot Key
	ON_MESSAGE(WM_HOTKEY,OnHotkey)

	//File Menu
	ON_COMMAND(11,OnOpenFrame)
	ON_COMMAND(12,OnSaveFrame)
	ON_COMMAND(13,OnCancel)
	
	//Capture Menu 
	ON_COMMAND(21,OnStartCapture)
	ON_COMMAND(22,OnStopCapture)
	
	//Filter Menu
	ON_COMMAND(31,OnFilterProtocol)
	ON_COMMAND(32,OnFilterPort)
	ON_COMMAND(33,OnFilterIPAddress)
	ON_COMMAND(34,OnFilterCustom)

	
	//View Menu
	ON_COMMAND(51,OnHide)
	
	//Help Menu
	ON_COMMAND(41,OnAbout)
	
	//ON_COMMAND(IDC_BUTTON2,ApplyFilter)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CCapturePacketDlg message handlers

BOOL CCapturePacketDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	//Intialize variables....
	packetcount=0;
	filter="";
	portfilter="";
	protofilter="";
	ipfilter="";
	IsVisible=TRUE;


		
	fprotocol=new FProtocol(NULL);
	fport=new FPort(NULL);
	fipaddress=new FIPAddress(NULL);
	fcustom=new FCustom(NULL);

	

    sfile=new CStdioFile();
   	
	


	menu=(CMenu*)this->GetMenu();
	datalist=(CListBox *) this->GetDlgItem(IDC_LIST2);
	layertree=(CTreeCtrl*) this->GetDlgItem(IDC_TREE1);
	list=(CListCtrl *)this->GetDlgItem(IDC_LIST1);
	
	

	datafont.CreateFont(16,10,0,0,FW_REGULAR,0,0,0,DEFAULT_CHARSET,0,0,0,0,"Courier New");
	datalist->SetFont(&datafont);
	datalist->SetHorizontalExtent(740);
	
	InitListCtrl();

	menu->EnableMenuItem(22,MF_GRAYED);
	menu->EnableMenuItem(23,MF_GRAYED);
	menu->EnableMenuItem(24,MF_GRAYED);

	// Disable all filters...
	menu->EnableMenuItem(31,MF_GRAYED);
	menu->EnableMenuItem(32,MF_GRAYED);
	menu->EnableMenuItem(33,MF_GRAYED);
	menu->EnableMenuItem(34,MF_GRAYED);

	
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	sniff=new Sniffer();
	if(sniff->GetDeviceList()==0)
	{
	menu->EnableMenuItem(21,MF_GRAYED);
	MessageBox("No network adapters are present");
	}	
	
	//Set tool tip text...
	treetip.Create(this,TTS_ALWAYSTIP );
	treetip.SetDelayTime(50);
	treetip.AddTool(layertree,"Double click on the header");
	
	layertree->SetToolTips(&treetip);



	
	//Register the hot key
	m_hotkeyid=501;
    RegisterHotKey(GetSafeHwnd(),m_hotkeyid,MOD_ALT,VK_F5);
	

	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CCapturePacketDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

HCURSOR CCapturePacketDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}



void CCapturePacketDlg::OnRowSelect(NMHDR* pNMHDR, LRESULT* pResult)
{
POSITION pos;
int index;

	pos=list->GetFirstSelectedItemPosition();
	
	if(pos==NULL) //No item selected...
	return;

	index=list->GetNextSelectedItem(pos);
	
	DisplayFrame(index);
	
}





void CCapturePacketDlg::OnTreeSelect(NMHDR* pNMHDR, LRESULT* pResult)
{
HTREEITEM selitem,paritem;	
	selitem=layertree->GetSelectedItem();
	if(selitem==NULL)
	return;

	paritem=layertree->GetParentItem(selitem);
		
	if(paritem!=NULL)
	return;

	//Continue if the selected item is the root item
	CString name=layertree->GetItemText(selitem);

	//Complete Frame
	if(name.Find("Frame",0)!=-1)
	{
		DisplayData(frame,framesize);
		return;
	}
	
	
	//Ethernet layer
	if(name.Find("Ethernet",0)!=-1)
	{
		DisplayData(frame,ETHER_LENGTH);
		return;
	}
	
	//ARP layer
	if(name.Find("ARP",0)!=-1)
	{
		DisplayData(frame+ETHER_LENGTH,ARP_LENGTH);
		return;
	}
	
	//IP layer
	if(name.Find("IP",0)!=-1)
	{
		DisplayData(frame+ETHER_LENGTH,IP_LENGTH);
		return;
	}
	
	//TCP layer
	if(name.Find("TCP",0)!=-1)
	{
		DisplayData(frame+ETHER_LENGTH+IP_LENGTH,TCP_LENGTH);
		return;
	}
	
	//UDP layer
	if(name.Find("UDP",0)!=-1)
	{
		DisplayData(frame+ETHER_LENGTH+IP_LENGTH,UDP_LENGTH);
		return;
	}
	
	//ICMP layer
	if(name.Find("ICMP",0)!=-1)
	{
		DisplayData(frame+ETHER_LENGTH+IP_LENGTH,ICMP_LENGTH);
		return;
	}
	
	//IGMP layer
	if(name.Find("IGMP",0)!=-1)
	{
		DisplayData(frame+ETHER_LENGTH+IP_LENGTH,IGMP_LENGTH);
		return;
	}
	
	
	
	//Data layer
	if(name.Find("Data",0)!=-1)
	{
		DisplayData(frame+dataoff,datasize);
		return;
	}
	
	// Check for some unhandled/new layer
	if(name.Find("Unknown",0)!=-1)
	{
		DisplayData(frame,-1);   //Clear the data....
		return;
	}
	

}




void CCapturePacketDlg::InitListCtrl()
{
		
	list->SetExtendedStyle(LVS_EX_FULLROWSELECT); 
	
	list->InsertColumn(0,"No",LVCFMT_LEFT,80);
	list->InsertColumn(1,"Time",LVCFMT_LEFT,70);
	list->InsertColumn(2,"Length",LVCFMT_LEFT,60);
	list->InsertColumn(3,"Frame Type",LVCFMT_LEFT,90);
	list->InsertColumn(4,"Protocol",LVCFMT_LEFT,80);
	list->InsertColumn(5,"SAddress",LVCFMT_LEFT,120);
	list->InsertColumn(6,"SPort",LVCFMT_LEFT,50);
	list->InsertColumn(7,"DAddress",LVCFMT_LEFT,120);
	list->InsertColumn(8,"DPort",LVCFMT_LEFT,50);
	list->InsertColumn(9,"Information",LVCFMT_LEFT,300);
}




void CCapturePacketDlg::OnHotkey(int id,UINT modifier,UINT vcode)
{

	if(IsVisible)
	{
	this->ShowWindow(SW_HIDE);
	IsVisible=FALSE;
	}
	else
	{
	this->ShowWindow(SW_SHOWNORMAL);
	this->SetFocus();
	IsVisible=TRUE;
	}

}


void CCapturePacketDlg::OnOpenFrame()
{
CFileDialog fd(1,0,0,0,"Text Files(*.txt)|*.txt|All Files|*.*||");
CString line;
BOOL ret;
int index,length;
char buffer[MAX_PACKET_SIZE];
CStdioFile tfile;
	
	
		if(fd.DoModal()==IDOK)
		{
		

			ret=tfile.Open(fd.GetPathName(),CFile::modeRead);

			if(ret==FALSE)
			{
			MessageBox("Unable to open the specified file");
			return;
			}
		
			tfile.ReadString(line);
			index=line.Find("Frame Length");
						
			if(index==-1)
			{
			MessageBox("Unrecognized format ");
			tfile.Close();
		 	return;
			}
			
			index=line.Find('=');
			
			if(index==-1)
			{
			MessageBox("Unrecognized format ");
			tfile.Close();
			return;
			}
			
			// Get the length of frame...
			index++;
			sscanf(((LPCTSTR)line)+index,"%d",&length);
			
			tfile.ReadString(line);   //dummy line...
			
			ret=tfile.Read(buffer,length); //
			
			if(ret!=length)
			{
			MessageBox("Frame data is corrupted...");
			tfile.Close();
		 	return;
			}
			
			//Read successfully....
			framesize=length;
			memcpy(frame,buffer,length);
			frameno=-1;
			DisplayData(frame,framesize);
			DisplayTree();
			
			tfile.Close();
			
		}


}

void CCapturePacketDlg::OnSaveFrame()
{
CFileDialog fd(0,0,0,0,"Text Files(*.txt)|*.txt|All Files|*.*||");
CString filename,ext;
CStdioFile tfile;
u_char *pdata;
char str[500],line[400],hex[100];
int linecount=0,limit,length,slen;
	

	if(datalist->GetCount()==0)
	{
	MessageBox("Please select the frame..");
	return;
	}

	fd.m_ofn.lpstrTitle="Save File";



	if(fd.DoModal()==IDOK)
	{
		
		filename=fd.GetPathName();
		ext=fd.GetFileExt();
		
		if(ext.IsEmpty())
		filename=filename+".txt";
	

		//Create the new file....
		tfile.Open(filename,CFile::modeCreate | CFile::modeWrite| CFile::typeBinary);
		
		sprintf(str,"Frame Length=%d",framesize);
		tfile.WriteString(str);

		sprintf(str,"\r\nFrame Data ...\r\n");
		tfile.WriteString(str);

		tfile.Write(frame,framesize);

		length=framesize;
		
		sprintf(str,"\r\n\r\nHex display of Frame");
		tfile.WriteString(str);

		
		while(length>0)
		{

			pdata=frame+linecount*16;

			limit=length<16?length:16;
			
			//print index
			sprintf(line,"\r\n 0x%.4x ",linecount*16);
						
			//print hex content (hex bytes)
			for(int i=0;i<limit;i++)
			{
				sprintf(hex,"%.2x ",pdata[i]);
				strcat(line,hex);
			}			
	
			if(limit<16)
			{
			sprintf(hex,"%*s",(16-limit)*3," ");
			strcat(line,hex);
			}
			
			slen=strlen(line);
			for (int  j=0; j<limit; j++)
			line[slen+j]=isprint(pdata[j])?pdata[j]:'.';
			line[slen+j]=0;
		
			tfile.WriteString(line);
			
			linecount++;
			length=length-16;
		}
	
		WriteToFile(&tfile);
		tfile.Close();
	}


}

void CCapturePacketDlg::WriteToFile(CStdioFile *tfile) 
{
eth_header *eh;
ip_header *iph;
tcp_header *tcph;
udp_header *udph;
icmp_header *icmph;
igmp_header *igmph;

char str[300];
int ip_hlen;


	tfile->WriteString("\r\n\r\n[ Ethernet Header ]\r\n");
	eh=(eth_header*)frame;
	DisplayEthernetHeader(eh,tfile);

	
	
	//Get ARP header
	if(ntohs(eh->type)==0x0806)
	{
		tfile->WriteString("\r\n\r\n[ ARP Header ]\r\n");
		DisplayARPHeader((arp_header*) (frame+ETHER_LENGTH) ,tfile);
	return;
	}
	
	//Reject frames other than IP/ARP frames....
	if(ntohs(eh->type)!=0x0800)
	return;

	
	//Get Internet Header
	tfile->WriteString("\r\n\r\n[ IP Header ]\r\n");
	iph=(ip_header*)(frame+ETHER_LENGTH);
	DisplayIPHeader(iph,tfile);


	//Get the length of IP Header
	ip_hlen=(iph->ver_ihl & 0xf)<<2;
	
	switch(iph->proto)
	{
		case 1: //ICMP
			tfile->WriteString("\r\n\r\n[ ICMP Header ]\r\n");
			icmph=(icmp_header*)(frame+ETHER_LENGTH+ip_hlen);
			DisplayICMPHeader(icmph,tfile);	
			dataoff=ETHER_LENGTH+ip_hlen+ICMP_LENGTH;
			datasize=framesize-dataoff;
		break;
		
		case 2: //IGMP
			tfile->WriteString("\r\n\r\n[ IGMP Header ]\r\n");
			igmph=(igmp_header*)(frame+ETHER_LENGTH+ip_hlen);
			DisplayIGMPHeader(igmph,tfile);	
			dataoff=ETHER_LENGTH+ip_hlen+IGMP_LENGTH;
			datasize=framesize-dataoff;
		break;
		
	

		case 6: //TCP
			tfile->WriteString("\r\n\r\n[ TCP Header ]\r\n");
			tcph=(tcp_header*)(frame+ETHER_LENGTH+ip_hlen);
			DisplayTCPHeader(tcph,tfile);	
			dataoff=ETHER_LENGTH+ip_hlen+TCP_LENGTH;
			datasize=framesize-dataoff;

		break;

		case 17: //UDP
			tfile->WriteString("\r\n\r\n[ UDP Header ]\r\n");
			udph=(udp_header*)(frame+ETHER_LENGTH+ip_hlen);
			DisplayUDPHeader(udph,tfile);
			dataoff=ETHER_LENGTH+ip_hlen+UDP_LENGTH;
			datasize=framesize-dataoff;
		break;

		default:
			tfile->WriteString("\r\n\r\n[ Unknown Header ]\r\n");
			dataoff=ETHER_LENGTH+ip_hlen;
			datasize=framesize-dataoff;
		
		}

	
	if(datasize==0)
	return;
	
	//Display Data 
	tfile->WriteString("\r\n\r\n[ Data ]\r\n");
	sprintf(str,"Data length = %d ",datasize);
	tfile->WriteString(str);

}








void CCapturePacketDlg::OnCancel() 
{
	sniff->CloseDevice();
	UnregisterHotKey(GetSafeHwnd(),m_hotkeyid);
	CDialog::OnCancel();
}




/**
*    Displays the dialog box for selecting device for
*    capture and then start the capture...
*
*/

void CCapturePacketDlg::OnStartCapture()
{
SelectDlg sd(sniff);

	// If the device is selected then start capture...
	
	if(sniff->devcount>0)
	{

		
		if(sd.DoModal()==IDOK)
		{
			
			if(sniff->OpenDevice(sd.selindex))
			{
			
			// clear all....	
			list->DeleteAllItems();
			datalist->ResetContent();
			layertree->DeleteAllItems();
			
			menu->EnableMenuItem(21,MF_GRAYED);
			menu->EnableMenuItem(22,MF_ENABLED);


			// Enable all filters...
			menu->EnableMenuItem(31,MF_ENABLED);
			menu->EnableMenuItem(32,MF_ENABLED);
			menu->EnableMenuItem(33,MF_ENABLED);
			menu->EnableMenuItem(34,MF_ENABLED);

		
			packetcount=0;

			sfile->Open("packet.txt",CFile::modeWrite | CFile::modeCreate | CFile::shareDenyWrite | CFile::typeBinary);
	 		sniff->StartCapture(this);
	
			}	
		}
		
	}
	else
	{
	MessageBox("No capture devices are present");
	}

}



void CCapturePacketDlg::OnStopCapture()
{
	
	sniff->StopCapture();
	
	sfile->Close();
	
	menu->EnableMenuItem(21,MF_ENABLED);
	menu->EnableMenuItem(22,MF_GRAYED);

	// Disable all filters...
	menu->EnableMenuItem(31,MF_GRAYED);
	menu->EnableMenuItem(32,MF_GRAYED);
	menu->EnableMenuItem(33,MF_GRAYED);
	menu->EnableMenuItem(34,MF_GRAYED);

}







void CCapturePacketDlg::OnFilterProtocol()
{
BOOL ret;
	if(fprotocol->DoModal()==IDOK)
	{
	
	//Check for valid combination....
	if(  fprotocol->protocol.CompareNoCase("ICMP")==0 || fprotocol->protocol.CompareNoCase("IGMP")==0)
	{
		if(portfilter.IsEmpty()==FALSE)
		{
		MessageBox("Uncheck the PortFilter to Apply this Protocol Filter");
		return;
		}
	}
	protofilter=fprotocol->protocol;
	
	if(ipfilter.IsEmpty())
	filter=protofilter+portfilter;    //add together all the 3 filters...
	else
	filter=ipfilter+" and "+protofilter+portfilter;

	
	sniff->PauseCapture();
	ret=sniff->ApplyFilter((char *)(LPCTSTR)filter);
	sniff->ResumeCapture();
	
	if(ret==TRUE)
	MessageBox("Filter applied successfully");
	

	// Disable the custom filter if it is enabled..
	if(fcustom->IsEnable)
	{
		fcustom->IsEnable=FALSE;
		menu->CheckMenuItem(34,MF_UNCHECKED);
	}
	
	
	}
	

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -