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

📄 pingtestdlg.cpp

📁 A ping test tool. Use to check ping speed and write a log over time. You can test your wlan connecti
💻 CPP
字号:
// PingTestDlg.cpp : implementation file
//
// if NOT for coop undef COOP
#define COOP
#undef COOP

#include "stdafx.h"
#include "PingTest.h"
#include "PingTestDlg.h"
#include "IPEXPORT.H"
#include "ICMPAPI.H"
#include "itc50.h"
#include "80211_Api.h"
#include "oemioctl.h"
#include "iphlpapi.h"
#pragma comment (lib, "iphlpapi.lib")

extern "C" BOOL KernelIoControl(DWORD dwIoControlCode, LPVOID lpInBuf, DWORD nInBufSize, LPVOID lpOutBuf, DWORD nOutBufSize, LPDWORD lpBytesReturned);


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

char logFileName[MAX_PATH]; 
TCHAR logFileNameW[MAX_PATH]; 

// Returns number of elements
#define dim(x) (sizeof(x) / sizeof(x[0]))   

//maximum count of Bars
#define MAXBARS 20

/////////////////////////////////////////////////////////////////////////////
// CPingTestDlg dialog

CPingTestDlg::CPingTestDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CPingTestDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CPingTestDlg)
	m_IPtxt = _T("192.168.128.238");
	m_Intervall = 1;
	m_LogToFile = FALSE;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CPingTestDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CPingTestDlg)
	DDX_Control(pDX, IDC_GRAPHIC, m_Graph);
	DDX_Control(pDX, IDC_LOGLIST, m_LogList);
	DDX_Text(pDX, IDC_IpAdr, m_IPtxt);
	DDX_Text(pDX, IDC_Intervall, m_Intervall);
	DDV_MinMaxInt(pDX, m_Intervall, 1, 300);
	DDX_Check(pDX, IDC_LogToFile, m_LogToFile);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CPingTestDlg, CDialog)
	//{{AFX_MSG_MAP(CPingTestDlg)
	ON_BN_CLICKED(IDC_StartTest, OnStartTest)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_StartTimer, OnStartTimer)
	ON_BN_CLICKED(IDC_LogToFile, OnLogToFile)
	ON_BN_CLICKED(IDC_btnReboot, OnbtnReboot)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CPingTestDlg message handlers

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

	// 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
	
	CenterWindow(GetDesktopWindow());	// center to the hpc screen

	// TODO: Add extra initialization here
#if COOP
	GetDlgItem(IDC_TestCount)->EnableWindow(false);
	GetDlgItem(IDC_StartTimer)->EnableWindow(false);
	GetDlgItem(IDC_LogToFile)->EnableWindow(false);
	SetWindowText(_T("PingTest v1.4 coop"));
	m_IPtxt = _T("10.3.1.83");
	RETAILMSG("COOP build");
#else
	GetDlgItem(IDC_TestCount)->EnableWindow(true);
	GetDlgItem(IDC_StartTimer)->EnableWindow(true);
	GetDlgItem(IDC_LogToFile)->EnableWindow(true);
	SetWindowText(_T("PingTest v1.4 standard"));
#endif

	GetDlgItem(IDC_IpAdr)->SetFocus();
	wsprintf(m_LogText, L""); //Clear LogText
	
	wsprintf(logFileNameW, L"\\PingTestLog.txt");
	wcstombs(logFileName, logFileNameW, dim(logFileName));

	//Graph Control
	m_Graph.SetUnit(UCM);  //Sets scale to cm
	//m_Graph.SetNumberOfBars(10);  //Number of bars to be shown, 
									//has been changed as default in GraphCtrl.cpp to avoid "Out of memory"
	for (int i=0; i<MAXBARS; i++)
	{
		m_Graph.SetBarColor(i,RGB(200,200,200)); //Sets the color to the bar of index 1
		m_Graph.SetBarValue(i,5*i); //Sets value to the bar of index 1
	}

	//number of pings in a block
	PingBlocks=4;
	return FALSE;  // return TRUE  unless you set the focus to a control
}

int CPingTestDlg::PingAddress(LPTSTR lpszPingAddr)
{
    TCHAR lpszOut[64];
	HANDLE hPing;
    BYTE bOut[32];
    BYTE bIn[1024];
    char cOptions[12];
    char szdbAddr[32];
    IP_OPTION_INFORMATION ipoi;
    PICMP_ECHO_REPLY pEr;
    struct in_addr Address;
    INT i, j, rc;
    DWORD adr;
	DWORD ping_good=0;
	DWORD ping_bad=0;
	static bar_count=0;

    // Convert xx.xx.xx.xx string to a DWORD. First convert the string    
	// to ASCII.    
	wcstombs (szdbAddr, lpszPingAddr, 31);
    if ((adr = inet_addr(szdbAddr)) == -1L)        
		return -1;
    // Open ICMP handle.    
	hPing = IcmpCreateFile ();
    if (hPing == INVALID_HANDLE_VALUE)        
		return -2;
    wsprintf (lpszOut, TEXT ("Pinging: %s"), lpszPingAddr);
	AddLog(lpszOut);
	//set Target for LogFile
	wsprintf(m_Target, lpszPingAddr);
    // Ping loop    
	for (j = 0;  j < PingBlocks;  j++) 
	{
		//Get Radio Stats
		GetRadioStats();
		// Initialize the send data buffer.        
		memset (&bOut, 0, sizeof (bOut));
		// Initialize the IP structure.        
		memset (&ipoi, 0, sizeof (ipoi));
        ipoi.Ttl = 32;
        ipoi.Tos = 0;
        ipoi.Flags = IP_FLAG_DF;
        memset (cOptions, 0, sizeof (cOptions));
        // Ping!        
		rc = IcmpSendEcho (hPing, adr, bOut, sizeof (bOut), &ipoi, bIn, sizeof (bIn), 1000);
        if (rc) 
		{            
			ping_good++;
			// Loop through replies.            
			pEr = (PICMP_ECHO_REPLY)bIn;
            for (i = 0; i < rc;  i++) 
			{                 
				Address.S_un.S_addr = (IPAddr)pEr->Address;
                // Format output string.                
				wsprintf (lpszOut, TEXT ("Reply from %hs: bytes:%d time:"), inet_ntoa (Address), pEr->DataSize);
                // Append round-trip time.
				if (pEr->RoundTripTime < 10)                    
					lstrcat (lpszOut, TEXT ("<10mS"));
                else
					wsprintf (&lpszOut[lstrlen(lpszOut)], TEXT ("%dmS"), pEr->RoundTripTime);
				wsprintf(m_RoundTrip, L"%d", pEr->RoundTripTime);
				AddLog(lpszOut);

				SetBarVal((long)pEr->RoundTripTime); //Sets value to the bar

                pEr++;
         	}        
		} 
		else 
		{            
			ping_bad++;
			lstrcpy (lpszOut, TEXT ("Request timed out."));
			AddLog(lpszOut);

			SetBarVal(0); //Sets value of a bar

			wsprintf(m_RoundTrip, L"-1");
        }    
	}    IcmpCloseHandle (hPing);
	wsprintf(lpszOut, L"Ping Stats Good: %00i, Bad: %00i", ping_good, ping_bad); 
	AddLog(lpszOut);
	return 0;
}

void CPingTestDlg::AddLog(TCHAR *txt)
{
	TCHAR str[3000];
	//Create the file
	if ((FirstStart) & (m_LogToFile == TRUE))
	{
		GetAPmac();
		GetSerialNumber();
		GetRadioMac();
		wsprintf(m_LogText, L"PingTest v1.3:\tFile:\t%s\t\nDevice SN:\t%s\tinitial AP Mac:\t%s", logFileNameW, m_DeviceSerialnumber, AccessPointMAC);
		writefile (m_LogText);

		wsprintf(m_LogText, L"Device MAC:\t%s\tTarget IP:\t%s", m_RadioMac, m_IPtxt);
		writefile (m_LogText);

		wsprintf(m_LogText,L"Time\tPingTime\tWLanStatus\tLinkSpeed\tSignal");
		writefile (m_LogText);
		FirstStart=FALSE;
	}
	CTime t = CTime::GetCurrentTime();
	
	int iHour = t.GetHour ();
	int iMinu = t.GetMinute();
	int iSeco = t.GetSecond();

	int i;
	wsprintf(str, L"%02i:%02i:%02i->%s", iHour, iMinu, iSeco, txt);
	wsprintf(m_Time, L"%02i:%02i:%02i", iHour, iMinu, iSeco);
	m_LogList.AddString(str);
	if (m_LogToFile == TRUE)
	{
		wsprintf(m_LogText, L"%s\t%s\t%s\t%s\t%s",
			m_Time,
			m_RoundTrip,
			m_RadioStatus,
			m_Speed,
			m_SignalStrength);
		if ( wcslen (m_LogText) > 18 ) //Avoid writing incomplete lines
			writefile(m_LogText);
	}
	i = m_LogList.GetCount();
	m_LogList.SetCurSel(i-1);

}

void CPingTestDlg::OnStartTest() 
{
	// TODO: Add your control notification handler code here
	int keep_alive = 1;
	TCHAR szTemp[255];
	char  szTempA[255];
	DWORD dwDestAddr;
	
	HadError = FALSE;

	// Disable Button during process
	if ( m_nTimer == 0 )
		GetDlgItem(IDC_StartTest)->EnableWindow(FALSE);

	// we need the actual IP
	UpdateData(TRUE);

	dumpAdapterInfos();
	wsprintf(szTemp, _T("Target IP: %s"), m_IPtxt);
	AddLog (szTemp);

	//Convert string ip to inet_addr
	wcscpy(szTemp, m_IPtxt);
	wcstombs(szTempA, szTemp, sizeof(szTemp)*sizeof(TCHAR));

	dwDestAddr = inet_addr(szTempA);
	if ( dwDestAddr == INADDR_NONE )
	{
		AddLog (L"IP address not valid");
		HadError = TRUE;
        goto Exit;
	}
	// Ping()
	wsprintf(szTemp, m_IPtxt);
	if ( PingAddress(szTemp) != 0 )
	{
		AddLog (L"Error in Ping()");
		HadError = TRUE;
		goto Exit;
	}
Exit:
	// Ensable Button after process
	if ( m_nTimer == 0 )
		GetDlgItem(IDC_StartTest)->EnableWindow(TRUE);
	if (HadError == TRUE)
	{
		if (m_nTimer != 0)
			OnStartTimer(); //Stop timer
		MessageBox(L"There was an error. See Log for details!", L"ERROR", MB_OK | MB_TOPMOST);
	}
	
}

void CPingTestDlg::OnTimer(UINT nIDEvent) 
{
	TCHAR szTemp[32];
	
	GetDlgItem(IDC_TestCount)->SetWindowText(_T("Starting..."));
	
	if (m_LogToFile != TRUE) //Do only if not logging to file
	{
		wsprintf (szTemp, L"Testing connection count: %3i", count);
		AddLog(szTemp);
	}
	wsprintf(szTemp, L"%3i", count);
	GetDlgItem(IDC_TestCount)->SetWindowText(szTemp);
	
	OnStartTest();
	count++;
	if (count == 3000)
	{
		MessageBox(L"Maximum TestCount=3000 reached", L"PingTest", MB_OK | MB_TOPMOST);
		OnStartTimer(); //Stop
	}
	CDialog::OnTimer(nIDEvent);
}

void CPingTestDlg::OnStartTimer() 
{
	// TODO: Add your control notification handler code here
	
	if (m_nTimer==0) //Timer has not been Started
	{
		UpdateData();
		PingBlocks=1;
		if (m_LogToFile == TRUE)
		{
			//Ask for file name
			//Init some values	
			TCHAR szFilters[] = _T ("Text files (*.txt)|*.txt|All files (*.*)|*.*||");
			TCHAR szDefExt[] = _T("txt");
			TCHAR szFileName[MAX_PATH];
			wsprintf(szFileName, L"%s", logFileNameW);
			//fill the dialog struct
			CFileDialog fileDlg( 
				FALSE,										//BOOL bOpenFileDialog,
				szDefExt,									//LPCTSTR lpszDefExt = NULL,
				szFileName,									//LPCTSTR lpszFileName = NULL,
				OFN_HIDEREADONLY | 
				OFN_PATHMUSTEXIST,							//DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
				szFilters,									//LPCTSTR lpszFilter = NULL,
				this										//CWnd* pParentWnd = NULL
				); 		
			//Get the path to the personal folder
			TCHAR szPath[MAX_PATH];
			if(SUCCEEDED(SHGetSpecialFolderPath (NULL, 
										 szPath, 
										 CSIDL_PERSONAL, 
										 FALSE))) 
				fileDlg.m_ofn.lpstrInitialDir = szPath;
			else
				fileDlg.m_ofn.lpstrInitialDir = L"\\";

			TCHAR szTitle[] = _T ("Select Filename for LogFile");
			fileDlg.m_ofn.lpstrTitle = szTitle;
			//Open the dialog
			if ( fileDlg.DoModal ()==IDOK ) 
			{
				TCHAR pathName[MAX_PATH];
				wsprintf (pathName, fileDlg.GetPathName().GetBuffer(128)); 
				if ( wcslen(pathName) == 0 )
					goto TimerExit;
				_tcscpy(logFileNameW, pathName);
				wcstombs(logFileName, logFileNameW, sizeof(logFileName)*sizeof(logFileName[0]));
				// Check if file exists
				FILE *fp;
				/*
				fp = fopen(logFileName, "r");
				if ( fp != NULL )
				{
					int ant = AfxMessageBox(L"Log-Datei existiert bereits. 躡erschreiben?", 
						MB_ICONQUESTION | MB_YESNO | MB_SETFOREGROUND);
					if ( (ant == IDNO) | (ant == IDCANCEL) )
					{
						fclose(fp);				
						goto TimerExit;
					}
					else
					{
						//Delete the File
						fclose(fp);				
				*/
						fp = fopen(logFileName, "w+");
						if ( fp != NULL )
							fclose(fp);
				/*
					}
				}
				*/
			}
			else
				goto TimerExit;

		}
		if ((m_Intervall < 1) || (m_Intervall >300) )
			return;
		m_LogList.ResetContent();
		FirstStart=TRUE;
		count=1;
		GetDlgItem(IDC_StartTimer)->SetWindowText(_T("Stop Timer"));
		GetDlgItem(IDC_StartTest)->EnableWindow(FALSE);
		GetDlgItem(IDC_LogToFile)->EnableWindow(FALSE);
		GetDlgItem(IDC_IpAdr)->EnableWindow(FALSE);
		GetDlgItem(IDC_Intervall)->EnableWindow(FALSE);
		m_nTimer = SetTimer(1, m_Intervall * 1000, 0);
	}
	else //Stop the Timer etc
	{
		KillTimer(m_nTimer); 
		m_nTimer = 0;
		PingBlocks=4;
		GetDlgItem(IDC_LogToFile)->EnableWindow(TRUE);
		GetDlgItem(IDC_StartTest)->EnableWindow(TRUE);
		GetDlgItem(IDC_StartTimer)->SetWindowText(_T("Start Timer"));	
		GetDlgItem(IDC_IpAdr)->EnableWindow(TRUE);
		GetDlgItem(IDC_Intervall)->EnableWindow(TRUE);
	}
TimerExit:
	;
}

int CPingTestDlg::writefile(LPTSTR filetext)
{

	/* File Write Function, written by professor chemicalX */
	FILE	*fp;						/* Declare FILE structure */
	TCHAR  szTemp[255];
	char  szTempA[255];

	wsprintf(szTemp, L"%s\n", filetext);
	wcstombs(szTempA, szTemp, wcslen(szTemp)*sizeof(TCHAR));

	fp = fopen(logFileName, "a+");

	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	/* First of we open the file supplied by the filename paremeter */

	/*
	 * in the "a+" mode for appending, so if it doesnt exist its created. 

⌨️ 快捷键说明

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