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

📄 test2dlg.cpp

📁 用VC编写的IP冲突防护器,借此可以熟悉网络编程.
💻 CPP
字号:
// test2Dlg.cpp : implementation file
//

#include "stdafx.h"
#include "test2.h"
#include "test2Dlg.h"






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


/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTest2Dlg dialog

CTest2Dlg::CTest2Dlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTest2Dlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CTest2Dlg)
	m_FakedMac = _T("");
	m_SendCount = 0;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CTest2Dlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTest2Dlg)
	DDX_Control(pDX, IDC_AdapterList, m_AdapterList2);
	DDX_Control(pDX, IDC_SRCIP, m_SRCIP);
	DDX_Text(pDX, IDC_FakedMac, m_FakedMac);
	DDV_MaxChars(pDX, m_FakedMac, 12);
	DDX_Text(pDX, IDC_SentCountShow, m_SendCount);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CTest2Dlg, CDialog)
	//{{AFX_MSG_MAP(CTest2Dlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CLOSE()
	ON_BN_CLICKED(IDC_Start, OnStart)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_Stop, OnStop)
	ON_LBN_SELCHANGE(IDC_AdapterList, OnSelchangeAdapterList)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTest2Dlg message handlers

BOOL CTest2Dlg::OnInitDialog()
{


  	CDialog::OnInitDialog();
	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here

	/* Retrieve the device list */
    if (pcap_findalldevs(&alldevs, errbuf) == -1)
    {
        error = "Error in pcap_findalldevs:";
		error += errbuf;
		MessageBox(error,NULL,MB_OK);
        exit(1);
    }
	/* Add the ethernet adapter item to ListBox*/
    i=0;
	
	for(d=alldevs,prev=alldevs;d;prev=d,d=d->next)
    {
		AdapterDes.Format("%s",d->name);
		AdapterDes.MakeUpper();			//取得网卡名称,全部大写
		if (AdapterDes.Find("WAN") != -1) //判断是否wan类型的,是就修改链表并跳过
		{
			if ( d == alldevs) alldevs=alldevs->next;
			else	prev->next=d->next;
			continue;
		}
		flag = PacketGetNetType( PacketOpenAdapter(d->name),&LinkInfo);//获取连接速度以显示
		if (d->description )
			AdapterDes.Format("%d.(%dMbps) %s", ++i,LinkInfo.LinkSpeed/1000000,
							  d->description);
		else AdapterDes.Format("%d. (%dMbps)%s",++i,LinkInfo.LinkSpeed/1000000,
							  d->name);
		m_AdapterList2.AddString(AdapterDes);
	}
	//没找到任何有有效网卡则退出
	if (m_AdapterList2.GetCount() == 0 )
	{
		MessageBox("You have no available network adapter!","Error",MB_OK |MB_ICONSTOP);
		exit (1);
	}
	//默认选定第一张网卡
	m_AdapterList2.SetCurSel(0);
	SetIPAndMac(m_AdapterList2.GetCurSel());



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

void CTest2Dlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// 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 CTest2Dlg::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();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTest2Dlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}


void CTest2Dlg::OnClose() 
{
	// TODO: Add your message handler code here and/or call default
	if (!alldevs) pcap_freealldevs(alldevs);

	CDialog::OnClose();
}

void CTest2Dlg::convertMac(u_char *str_mac, u_char *network_mac)
{
         char             tempString1[16]  = "";
         char             tempString2[3]   = "";
         u_short          tempUshort       = 0;
         int 	      i;
         strncpy( tempString1, (const char *)str_mac , 16 );
         tempUshort = strlen( tempString1 );
         if ( tempUshort == 12 )
         {
        	tempString2[2] = '\0';
         	for ( i = 0; i < 6; i++ )
                {
             		tempString2[0] = tempString1[ i << 1 ];
					tempString2[1] = tempString1[ ( i << 1 ) + 1 ];
             		network_mac[i]   = ( u_char )strtoul( tempString2, NULL, 16 );
                }  /* end of for */ 
         }

}


void CTest2Dlg::OnStart() 
{
	// TODO: Add your control notification handler code here
		//打开句柄做好发包准备
	if ( !UpdateData(TRUE) ) return;
//	SetIPAndMac(m_AdapterList2.GetCurSel());
	/* Jump to the selected adapter */
 	for(d=alldevs, i=0; i< m_AdapterList2.GetCurSel();d=d->next, i++);
    /* Open the adapter */
    if ( (adhandle= pcap_open_live(d->name, // name of the device
                             65536,     // portion of the packet to capture. 
                             // 65536 grants that the whole packet will be captured on all the MACs.
                             1,         // promiscuous mode
                             1000,      // read timeout
                             errbuf     // error buffer
                             ) ) == NULL)
    {
        MessageBox("Unable to open the adapter!",NULL,MB_OK);
        /* Free the device list */
        pcap_freealldevs(alldevs);
        return;
    }
	//构造arp包
	convertMac ( (u_char *)m_FakedMac.GetBufferSetLength(12),packet.ether_srcmac);
	convertMac ( (u_char *)"FFFFFFFFFFFF",packet.ether_dstmac);
	packet.ether_type		= 0x0608;
	packet.hardwaretype		= 0x0100; //10M ethernet
	packet.protocoltype		= 0x0008;
	packet.h_len			= 0x06;
	packet.p_len			= 0x04;
	packet.op				= 0x0100;
	convertMac ( (u_char *)m_FakedMac.GetBufferSetLength(12),packet.s_ha);
	m_SRCIP.GetAddress(packet.s_pa[0],packet.s_pa[1],packet.s_pa[2],packet.s_pa[3]);
	convertMac ( (u_char *)"000000000000",packet.t_ha);
	m_SRCIP.GetAddress(packet.t_pa[0],packet.t_pa[1],packet.t_pa[2],packet.t_pa[3]);
	packet.t_pa[3] = 0x01;
	for (i=0;i<18;i++) packet.padding[i] = 0x00;
	SetTimer (1,500,NULL);

}

void CTest2Dlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	pcap_sendpacket(adhandle,(u_char *)&packet,60);
	m_SendCount++;
	UpdateData(FALSE);
	if (m_SendCount > 9999999)
	{
		m_SendCount = 0;
		UpdateData(FALSE);
		PostMessage(WM_COMMAND,(BN_CLICKED << 16) + IDC_Stop,NULL);
		
	}

}

void CTest2Dlg::OnStop() 
{
	// TODO: Add your control notification handler code here
	KillTimer(1);
	pcap_close (adhandle);
}

VOID CTest2Dlg::SetIPAndMac(int SelectedAdapterNum)
{
	ULONG	IoCtlBufferLength = (sizeof(PACKET_OID_DATA)+sizeof(ULONG)-1);
	
	/* Jump to the intially selected adapter */
  	for(d=alldevs, i=0; i< SelectedAdapterNum;d=d->next, i++);
	//获取ip地址
	sockaddr_in_ptr = (sockaddr_in *)d->addresses->addr;
	LocalIPtmp		= (DWORD)sockaddr_in_ptr->sin_addr.S_un.S_addr;
	LocalIP			=  (LocalIPtmp << 24)					//ip首字节
					  +((LocalIPtmp << 8 ) & (0x00FF0000))
					  +((LocalIPtmp >> 8 ) & (0x0000FF00))
					  +(LocalIPtmp >>24);
	//设置ip控件内容
	m_SRCIP.SetAddress(LocalIP);
	//设置mac控件内容
	AdapterObject = PacketOpenAdapter(d->name);
	OidData = (PPACKET_OID_DATA) GlobalAllocPtr(GMEM_MOVEABLE | GMEM_ZEROINIT,IoCtlBufferLength);
	OidData->Length = 6;
	OidData->Oid = OID_802_3_CURRENT_ADDRESS;
	flag = PacketRequest (AdapterObject,FALSE,OidData);
    pmac = OidData->Data;
	m_FakedMac.Format("%02x%02x%02x%02x%02x%02x",
					*pmac,*(pmac+1),*(pmac+2),*(pmac+3),*(pmac+4),*(pmac+5));
	GlobalFreePtr (OidData);
	UpdateData(FALSE);
	return;
}

void CTest2Dlg::OnSelchangeAdapterList() 
{
	// TODO: Add your control notification handler code here
	SetIPAndMac(m_AdapterList2.GetCurSel());
}






⌨️ 快捷键说明

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